In the book The Busy Coders Guide to Android Development from CommonsWare, there is a chapter explaining how to work with the context menus.
In one example in that chapter, the context menu offers option for removing item from a list view that is generated from an ArrayList<String>
object named words
.
In the example the onContextItemSelected
method is implemented like this:
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:
...
}
The line where adapter.remove(...)
is called seems strange to me because of following fact:
Let's say the words
object contains following items (in that order)
- alfa
- beta
- gama
- alfa
Now, when user loads the context menu upon the 2nd alfa and selects the option for removing it, the mentioned line actually removes the 1st alfa. And that seems wrong to me.
Instead, I would do something 开发者_开发百科like this:
...
words.remove(info.position);
adapter.notifyDataSetChanged();
...
I'm not that good in Java and Android programming, so I would like to hear your opinion to this, because I want to be sure I understand well how adapters should be used.
Your idea sounds good.
The example is defunct if it behaves like you have described and you should tell Mark about it so he can check it as well (he'll probably do it anyway since he is very active on this site).
精彩评论