arvin arvin - 11 months ago 128
Android Question

Xamarin: List View Item ItemClick event triggers multiple times

I'm working on an app where I load data from my website using web services when I click a back or next button it will load again the data from the web service and then load those data on my custom PostAdapter class then load that adapter to my list view item

private async void LoadPosts(int year, int month){
IPostService postService = new PostService();

var posts = await postService.GetPosts(year, month);

PostAdapter adapter = new PostAdapter(Activity, posts.ToList();

_lstView.Adapter = adapter;

_lstView.ItemClick += _lstView_ItemClick;

private void _lstView_ItemClick(object sender, AdapterView.ItemClickEventArgs e){
var item = _lstView.GetItemAtPosition(e.Position).Cast<Post>();

var bundle = new Bundle();
bundle.PutInt("post_id", item.ID);

var nextFragment = new PostDetailFragment { Arguments = bundle };

var fragmentTransaction = this.Activity.SupportFragmentManager.BeginTransaction().Replace(Resource.Id.content_frame, nextFragment).Commit();

private void _btnPrev_Click(object sender, EventArgs e){
_selectedDate = _selectedDate.AddMonths(-1);

LoadPosts(_selectedDate.Year, _selectedDate.Month);

Now when I clicked previous button 3 times, then click item list view once. It will trigger 3 times the item click event of list view item. Any ideas?

Answer Source

You need to move this line outside of your LoadPosts method, probably to whatever the equivalent of the onCreate is

_lstView.ItemClick += _lstView_ItemClick;

The reason you're getting 3 event clicks is because every time the posts are loading, you're adding another event handler to the ListView.