2013-03-25 70 views
0

我一直在嘗試使用上下文菜單從列表中的一行中獲取文本。到目前爲止,我能夠使用我的row.xml文件中的id獲取文本名稱。但是,當我在列表中選擇另一行時,它將得到包含在列表第一行中的同名而不是我選擇的那一行。使用上下文菜單從列表中獲取文本

public boolean onContextItemSelected(MenuItem item) 
{ 
    AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); 

    if(item.getTitle()=="Get") 
    { 
     TextView textView = (TextView) this.findViewById(R.id.names); 
     String text = textView.getText().toString(); 

     //Then pass value retrieved from the list to the another activity 
    } 
} 

row.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 

<TextView 
    android:id="@+id/names" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    /> 

<TextView 
    android:id="@+id/pNumbers" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    /> 
</LinearLayout> 
+2

使用'String.equals'或'String.equalsIgnoreCase'來比較字符串而不是'==' – 2013-03-25 15:26:55

回答

0

你從你可以檢索所有的列表項數據適配器位置測試info.position

然後。

2

這不是正確的做法。您應該使用AdapterContextMenuInfo.position來獲取列表中數據的索引,然後將該數據傳遞給新的活動。

AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();  
switch(item.getItemId()) { // using the id is the proper way to determine the menu item 
    case R.id.menu_get: 
     Object data = mListAdapter.getItem(info.position); 
     // do something interesting with the data 
     return true; 
} 
+0

嗨,感謝您的回覆。被getId()假設爲getItemId()? 「menu_get」還會與包含菜單項的xml文件關聯嗎?我編程創建了我的上下文菜單。 – user1832478 2013-03-25 16:22:27

+0

是的,它應該是getItemId()。爲什麼做而不是使用XML?如果以編程方式創建它,您仍然可以分配一個ID。 – 2013-03-25 16:56:05

+0

我對Android很新穎我正在學習一個教程,展示瞭如何創建上下文菜單,並且它是以編程方式完成的,現在我更改了代碼以使用xml作爲菜單。我仍然不知道如何使用信息位置來獲取我想要的文本。 – user1832478 2013-03-25 17:07:57