在掌握 ListView 时,通常会忽略使用 notifyDataSetChanged() 的必要性。下面是如何填充和刷新 ListView 的基本概要。
为您的元素列表创建一个 ArrayList、一个 ListView 来显示它们,以及一个 ArrayAdapter 来连接它们:
private ArrayList<String> mMyElements;
private ListView mMyListView;
private ArrayAdapter<String> mMyArrayAdapter;
设置您的 ListView:
mMyListView = (ListView)findViewById(R.id.myListView);
mMyListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); // There are other ChoiceModes available,
// but I'm guessing this is the most likely one you want for your situation.
设置您的 ArrayAddapter 并将其分配给 ListView:
mMyArrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_activated_1, mMyElements);
mMyListView.setAdapter(mMyArrayAdapter);
现在您可以通过更改 ArrayList 中包含的内容来更改 ListView 中显示的内容。使用 notifyDataSetChanged() 向 ArrayAdapter 发出信号,它需要更新 ListView 的显示:
...
// Code which changes the elements contained in the ArrayList
// For example..
myElements.add(x);
myElements.remove(y);
...
// Notify the ArrayAdapter that it's ArrayList has changed.
mMyArrayAdapter.notifyDataSetChanged(); // This line is vital to get the altered ArrayList to display.
mMyListView.clearChoices(); // You may want to clear any old selections from the ListView when you refresh the display.
<Additional>
如果“重新膨胀”是指您的 GridView 和 ListView 位于不同的 Activity 或 Fragment 中,那么您需要做的就是在它们之间导航时维护 ArrayList myElements。您可以按意图在它们之间传递 ArrayList。