Is it okay to change a ListView's adapter dynamically?

Jeff Axelrod picture Jeff Axelrod · Mar 26, 2012 · Viewed 12.4k times · Source

Instead of creating multiple activities, I would like to change the ArrayAdapter of the ListView as needed. I don't see any mention in the API about whether or not it is okay to call setAdapter() more than once.

To be more specific, say I would like to start an activity that has a ListView. In this example, the ListView is initialized with a listView.setAdapter(this) from, say, a CategoryArrayAdapter.

Then a user selects a category. Without starting a new activity, the code will set a new adapter for the same ListView. The new adapter, say ItemArrayAdapter calls listView.setAdapter(this).

Does someone have experience having done this successfully or know of a specific reason why this shouldn't be done?

Answer

yorkw picture yorkw · Mar 27, 2012

I don't see any mention in the API about whether or not it is okay to call setAdapter() more than once.

The simple answer is YES, and I have done similar sort of things before.

This is exactly the reason why Adapter is existed and provided in the API. The actual content (Model) and how it is rendered (View) for each list items is isolated and implemented inside android.widget.Adapter, instead of directly bound to android.widget.AdapterView. As long as your adapter is properly implemented, you can swap/change the actual underlying adapter that bound to the ListView, simply by calling the setAdapter() method.