我目前有一项扩展ListActivity
我使用ListAdapter
对数据库中的条目进行活动。
我将膨胀的条目作为上下文菜单操作,但是我希望能够在单击时从所选ListView中的TextViews
之一获取值,这是我用{{获得的} 1}}。
问题是,当长时间按下激活上下文菜单时,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监听器?或者我是以错误的方式来做这件事的?
答案 0 :(得分:0)
您可以在用户长按listview项目后调用ListView.setOnItemLongClickListener(...)
和AlertDialog.Builder.setItems(CharSequence[] items, DialogInterface.OnClickListener listener)
来显示上下文菜单。
答案 1 :(得分: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());
方式好,效果很好!