[英]How to get the Button view which triggered a Context Menu?
I'm creating dynamically Button views with a context menu. 我正在使用上下文菜单动态创建Button视图。 When a context menu item is selected, I would like to retrive the Button view which triggered the context menu. 当选择上下文菜单项时,我想要检索触发上下文菜单的Button视图。
This is how I create the button : 这是我创建按钮的方式:
// Create a new button
Button buttonView = new Button(this);
// Set button text
buttonView.setText("MyButton");
// Set on click listener
buttonView.setOnClickListener( new ButtonClickHandler() );
// Register for context menu
registerForContextMenu(buttonView);
This is how I create the context menu : 这是我创建上下文菜单的方式:
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
And this is how I handle selected items : 这就是我处理所选项目的方式:
public boolean onContextItemSelected(MenuItem item) {
// Get extra menu information about the item selected
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
//
switch (item.getItemId()) {
case R.id.delete:
// Retrieve selected button text
String btnText = ((Button) info.targetView).getText().toString();
// etc...
return true;
default:
return super.onContextItemSelected(item);
}
}
The issue is that "(AdapterContextMenuInfo) item.getMenuInfo()" returns null, ie there is no extra information about the item. 问题是“(AdapterContextMenuInfo)item.getMenuInfo()”返回null,即没有关于该项的额外信息。 I was expecting to get the Button view in info.targetView. 我期待在info.targetView中获取Button视图。 Apparently this works only for ListView, because AdapterView takes care of populating this extra info. 显然这只适用于ListView,因为AdapterView负责填充这些额外的信息。
I guess I should do something in "onCreateContextMenu" to attach this information. 我想我应该在“onCreateContextMenu”中做一些事情来附加这些信息。 A sample code to attach this information would be very much welcomed. 附上此信息的示例代码将非常受欢迎。
Thanks 谢谢
用于创建上下文菜单的Button
是传递给onCreateContextMenu
的View
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.