简体   繁体   中英

Android ListView within fragment doesn't refresh without a button click

My ListView doesn't refresh its contents when I call the appropriate method unless the method was invoked with a button click.

The follow example code is how my test button works (temporary button to check to see if it was a problem with my refresh code):

testBtn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
       exampleRefresh();
    }
});

And the method it calls:

public void exampleRefresh() {
    exampleAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, arrayOfItems());
    exampleListView.setAdapter(exampleAdapter);
}

This works fine.

However, if I call exampleRefresh() in the switch statement for a context menu, nothing happens. Again, when I click the test button, the ListView refreshes instantly. These are calling the same method, I don't understand the issue.

I have tried adding nofifyDataSetChange() , but it doesn't work. The ListView only refreshes when I invoke a button press.

It's also worth noting that even if I call the method on the invoke of a context menu, it refreshes. It does not do anything without an invoke, it appears.

Any help will be very much appreciated.

have you tried to

exampleAdapter = new ArrayAdapter<String>();
exampleAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, arrayOfItems());
exampleListView.setAdapter(exampleAdapter);

this should force it to clear and re-add the

Try invoking notifyDataSetChange() from exampleListView.post() like this:

exampleListView.post(new Runnable() {

    public void run() {
         exampleAdapter.notifyDatasetChange();
    }

}

if you are changing data in list and then you want to refresh listview then dont call setadapter method again. just call below method:

exampleAdapter.notifyDataSetChange();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM