使用上下文菜单从列表中获取文本
我一直在尝试使用上下文菜单从列表中的一行中获取文本。到目前为止,我能够使用我的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>
你从你可以检索所有的列表项数据适配器位置测试info.position
然后。
这不是正确的做法。您应该使用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;
}
嗨,感谢您的回复。被getId()假设为getItemId()? “menu_get”还会与包含菜单项的xml文件关联吗?我编程创建了我的上下文菜单。 – user1832478 2013-03-25 16:22:27
是的,它应该是getItemId()。为什么做而不是使用XML?如果以编程方式创建它,您仍然可以分配一个ID。 – 2013-03-25 16:56:05
我对Android很新颖我正在学习一个教程,展示了如何创建上下文菜单,并且它是以编程方式完成的,现在我更改了代码以使用xml作为菜单。我仍然不知道如何使用信息位置来获取我想要的文本。 – user1832478 2013-03-25 17:07:57
使用'String.equals'或'String.equalsIgnoreCase'来比较字符串而不是'==' – 2013-03-25 15:26:55