Skip to content Skip to sidebar Skip to footer

Listview Does Not Show Changes Until Focus Changes After Notifydatasetchanged

I have an AlertDialog with a ListView set to multiple selection on it. It also has a Button on it. The Button open another AlertDialog that if ok'ed will remove the selected items

Solution 1:

By calling

((ArrayAdapter) list.getAdapter()).notifyDataSetChanged();

you get a fresh adapter which is almost certainly not identical to the anonymous adapter you used to populate your list in the first instance.

See also the documentation for ListView.getAdapter()

Returns the adapter currently in use in this ListView. The returned adapter might not be the same adapter passed to setAdapter(ListAdapter) but might be a WrapperListAdapter.

From the point of view of this fresh adapter, the data set hasn't changed because the changes happened way before it was instantiated.

To solve your problem, make your list and your list adapter members of your activity class (or the scope where you want to keep them alive):

private ArrayList<String>    keys;
private ArrayAdapter         myAdapter;
private ListView             list;

Then in your "onCreate()"

keys = ...;     // initialization of ArrayList with the needed data 
myAdapter = newArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_activated_1,
                    keys);
list = (ListView) view.findViewById(R.id.list_questions_edit_rack);
list.setAdapter(myAdapter);

This way, in your "OnClickListener" you can notify "myAdapter":

keys.addAll(map.keySet());
myAdapter.notifyDataSetChanged();

Hope this helps :)

Solution 2:

You can tweak it, by granting focus to another view, and then requesting it back:

view.requestFocus();

You can also use:

view.requestFocusFromTouch();

Post a Comment for "Listview Does Not Show Changes Until Focus Changes After Notifydatasetchanged"