ListView does not show changes until focus changes after notifyDataSetChanged

一曲冷凌霜 提交于 2019-12-02 04:04:29

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 = new ArrayAdapter<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 :)

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

view.requestFocus();

You can also use:

view.requestFocusFromTouch();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!