3
在书中来自CommonsWare的Android Development开发指南中,有一章解释了如何使用上下文菜单。使用阵列适配器或使用下层数据操作?
在该章节的一个示例中,上下文菜单提供了从列表视图中删除项目的选项,该列表视图是从名为words
的ArrayList<String>
对象中生成的。
在这个例子中onContextItemSelected
方法的实现是这样的:
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
ArrayAdapter<String> adapter=(ArrayAdapter<String>)getListAdapter();
switch (item.getItemId()) {
case R.id.remove:
adapter.remove(words.get(info.position));
return true;
default:
...
}
其中adapter.remove(...)
被称为该行觉得奇怪,因为下面的事实我:
比方说,words
对象包含以下项目(按照这个顺序)
- 阿尔法
- 测试版
- 伽马
- 阿尔法
现在,当用户在该第二阿尔法加载的上下文菜单并选择选项,可以消除它,所提到的行实际上消除了阿尔法。这对我来说似乎是错误的。
相反,我会做这样的事情:
...
words.remove(info.position);
adapter.notifyDataSetChanged();
...
我不是用Java和Android编程的好,所以我想听听你的意见这一点,因为我要确保我很好理解适配器应该如何使用。