[英]Trying to get a selected view from onContextItemSelected
我目前有一個擴展ListActivity
的主要活動
我使用帶有來自數據庫條目的ListAdapter
活動。 我讓膨脹的條目充當上下文菜單,但是我希望能夠在單擊時從選定的ListView內的一個TextViews
獲取值,該值是通過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偵聽器? 還是我走錯路了?
您可以在用戶長按列表視圖項目后AlertDialog.Builder.setItems(CharSequence[] items, DialogInterface.OnClickListener listener)
調用ListView.setOnItemLongClickListener(...)
和AlertDialog.Builder.setItems(CharSequence[] items, DialogInterface.OnClickListener listener)
以顯示上下文菜單。
好的,事實證明,這確實非常容易實現。 在我的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());
方式不錯,效果很好!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.