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?
This example demonstrates how do I dynamically update a ListView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
In Android development, any time we want to show a vertical list of scrollable items we will use a ListView which has data populated using an Adapter . The simplest adapter to use is called an ArrayAdapter because the adapter converts an ArrayList of objects into View items loaded into the ListView container.
An Adapter is responsible for creating and binding data to views. An Adapter isn't an actual view, but instead produces them. An AdapterView is a ViewGroup that gets its child views from an Adapter . E.g. a ListView has a child view for each row in its list.
To refresh the ListView in Android, call notifyDataSetChanged() method on the Adapter that has been set with the ListView. Also note that the method notifyDataSetChanged() has to be called on UI thread.
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.
Resetting the adapter is ok, but notice, that there might be a GUI glitch when doing so, as the view whose adapter is being changed has to be redrawn with the new data. Aside from this you should be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With