2013-05-29 25 views
0

得到一個選擇的視我現在有一個擴展ListActivity試圖從onContextItemSelected

我膨脹的活動與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偵聽器?還是我以錯誤的方式去做這件事?

回答

0

您可以在用戶長按列表視圖項目後調用ListView.setOnItemLongClickListener(...)AlertDialog.Builder.setItems(CharSequence[] items, DialogInterface.OnClickListener listener)來顯示上下文菜單。

+0

謝謝你的回覆,但我有點困惑。我看到如何設置listview onLonClick監聽器是有幫助的,但我不知道如何描述它,在省略號(...)中放置什麼。你的意思是我必須讓一個監聽器啓動上下文菜單嗎?或者是我真的會創建一個AlertDialog,它將列出菜單項,並充當上下文菜單? – user2338256

0

好吧,事實證明這確實很容易實現。在我的listItemClicklistener我不得不註冊一個文本菜單的列表項,然後打開右鍵菜單:

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()); 

路好,作品大!