0

我目前有一项主要活动可以扩展ListActivity

我正在ListAdapter使用数据库中的条目来夸大活动。我将膨胀的条目作为上下文菜单操作,但我希望能够在TextViews单击选定的 ListView 时从其中一个内部获取值,这是我用OnListItemClick listener.

问题是,当长按激活上下文菜单时,OnItemClickListener不会注册,我无法ListView从常规短按中获取值。的onListItemClick具有View单击时的可见性,但onContextItemSelected没有,它仅具有 的可见性MenuItem

public class EntryActivity extends ListActivity
{ 
   String currentItemName;

   @Override
   protected void onListItemClick(ListView l, View v, int position, long id) 
   {
       //The Value i need is this: currentItemName, 
       //and i need it to register when a list item is clicked
       TextView curName =(TextView)v.findViewById(R.id.txtName) ;
       currentItemName = curName.getText().toString(); 
   }

   //I need to use the String obtained from the click in the context menu
   //to call a method, but a long click makes the onContextItemSelected 
   //be called, so onItemClickListener is never called, and i cant get the string
   @Override
   public boolean onContextItemSelected(MenuItem item ) 
   {
      switch(item.getItemId())
      {
         case ADD_ONE: 
            methodCalled(currentItemName);
            break;
      }
   }

   //I am inflating the list with a DataAdapter and a ListAdapter
   private void refresh()
   {
      //create an array the size of the cursor(one item per row)
      InventoryItem[] items = new InventoryItem[c.getCount()];

      //create and set the DataAdaptor with the array of inventory items, to the 
      //inventoryList layout
      da = new DataAdapter(this,  R.layout.inventorylist, items);
      setListAdapter(da);      
   }
}

有什么方法可以使我单击的视图对 contextMenu 侦听器可用?还是我以错误的方式解决这个问题?

4

2 回答 2

0

在用户长按列表视图项目后,您可以调用ListView.setOnItemLongClickListener(...)并显示上下文菜单。AlertDialog.Builder.setItems(CharSequence[] items, DialogInterface.OnClickListener listener)

于 2013-05-29T01:53:22.207 回答
0

好的,事实证明这真的非常容易完成。在我的 listItemClicklistener 中,我只需为 contextMenu 注册 ListItem,然后打开上下文菜单:

    protected void onListItemClick(ListView l, View v, int position, long id) 
{

    Cursor c = db.getAllItems(); 
    c.moveToFirst(); 

    //get and store the row that was clicked
    currentRow = position;    

    //register this item for a context menu 
    registerForContextMenu(l);
    //open the context menu
    openContextMenu(l);


}

并且必须将此行添加到我的 OnCreate 方法中:

registerForContextMenu(getListView());

很好,很好用!

于 2013-05-31T01:34:08.147 回答