android – 如何根据ListActivity中长按的项目设置特定的上下文菜单?

前端之家收集整理的这篇文章主要介绍了android – 如何根据ListActivity中长按的项目设置特定的上下文菜单?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个列表活动,我选择手动添加第一个项目“添加新项目…”.

我使用registerForContextMenu(getListView())注册了整个列表视图的上下文菜单;直接进入onCreate.

构建上下文菜单时,系统调用onCreateContextMenu(ContextMenu菜单,View v,ContextMenuInfo menuInfo). View v是listView,我找不到一种方法来知道列表视图中的哪个项目被长按.

我可以创建一个xml布局,其中包含“添加新项目…”的布局,然后添加一个listview,它将由活动填充,并且会对上下文菜单做出反应,但我确信有一种在没有任何xml布局的情况下解决此问题的方法.

我尝试使用registerForContextMenu在listview中注册每个视图,但是listview不再响应touch.

这是我的活动代码列表:

  1. public class AMain extends ListActivity {
  2. private Listlogo = (ImageView) itemLayout.findViewById(R.id.logo);
  3. TextView pregName = (TextView) itemLayout.findViewById(R.id.pregName);
  4. if (position == 0) {
  5. itemLayout.setFocusable(false);
  6. itemLayout.setFocusableInTouchMode(false);
  7. pregName.setText(getString(R.string.addPreg));
  8. } else {
  9. logo.setVisibility(View.INVISIBLE);
  10. pregName.setText(pregList.get(position-1));
  11. }
  12. itemLayout.setId(position);
  13. return itemLayout;
  14. }
  15. }
  16. @Override
  17. protected void onListItemClick(ListView l,int position,long id) {
  18. super.onListItemClick(l,position,id);
  19. if (position == 0) {
  20. startActivity(prepareIntent(AShowPregnancy.class,0));
  21. } else {
  22. showPregnancy(position-1);
  23. }
  24. }
  25. void showPregnancy(int pregId) {
  26. startActivity(prepareIntent(AShowPregnancy.class,pregId));
  27. }
  28. void editPregnancy(int pregId) {
  29. startActivity(prepareIntent(ANewPregnancy.class,pregId));
  30. }
  31. Intent prepareIntent(Class

谢谢阅读.希望你能帮忙.

最佳答案
哦,天哪,再一次.我发现自己该怎么做,这比简单容易.

  1. AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
  2. // info.position is the position in the ListView

我恨我自己 :)

猜你在找的Android相关文章