[英]menuitem.getmenuinfo() returns null for dynamically created views
I have a ScrollView
with an embedded RelativeLayout
with an embedded LinearLayout
. 我有一个带有嵌入式RelativeLayout
和嵌入式LinearLayout
的ScrollView
。
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingLeft="16dp" android:paddingRight="16dp" android:id="@+id/relativeLayout">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_below="@+id/Today"
android:layout_alignParentLeft="true" android:id="@+id/linearLayoutToday"
android:animateLayoutChanges="true">
</LinearLayout>
</RelativeLayout>
</ScrollView>
I want to add a context menu for CheckBox
objects, which are added dynamically as shown below. 我想为CheckBox
对象添加一个上下文菜单,该菜单将如下所示动态添加。
private void addItem() {
CheckBox ch = new CheckBox(this);
ch.setText("Test");
registerForContextMenu(ch);
linearLayoutToday.addView(ch);
}
The issue occurs in the onContextItemSelected
method, as the value returned from item.getMenuInfo()
is always null. 该问题发生在onContextItemSelected
方法中,因为item.getMenuInfo()
返回的值始终为null。
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
System.out.println(info.targetView);
return true;
}
Does anyone know how to resolve this issue? 有谁知道如何解决这个问题?
This problem was caused because to add a context menu to all children, you simply add a context menu to the parent. 造成此问题的原因是,要将上下文菜单添加到所有子级,只需将上下文菜单添加到父级。 However, this is only supported with other views (eg ListView), not layouts. 但是,仅其他视图(例如ListView)支持此功能,而布局不支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.