在我的代码中,我必须监听多个上下文菜单:
Button btn1= (Button) findViewById(R.id.btn1);
registerForContextMenu(btn1);
Button edit_text1= (Button) findViewById(R.id.edit_text1);
registerForContextMenu( edit_text1 );
现在在onContextItemSelected
我希望得到女巫小部件必须要改变文字。例如:
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
long buttonId = info.id;
switch ( item.getItemId () ){
case 1:
/* IF USER REQUEST CONTEXT MENU ON btn1 */
btn1.setText( "OK" );
/* IF USER REQUEST CONTEXT MENU ON edit_text1 */
edit_text1.setText( "" );
}
return super.onContextItemSelected(item);
}
很遗憾,java.lang.NullPointerException
info.id
错误
更新发布
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle( R.string.choose_selection );
view_id = v.getId();
menu.add(0, view_id, 0, getResources ().getString ( R.string.clear ) );
menu.add(0, view_id, 0, getResources ().getString ( R.string.cut ) );
menu.add(0, view_id, 0, getResources ().getString ( R.string.copy ) );
}
@Override
public boolean onContextItemSelected(MenuItem item) {
Log.e("itemID ", item.getItemId ()+"");
Log.e("view_id ", view_id+"");
switch ( item.getItemId () ){
case 1:
break;
}
return super.onContextItemSelected(item);
}
在onContextItemSelected
,item.getItemId ()
和view_id
中的是相同的,在获取父上下文菜单后如何获取菜单项ID?
答案 0 :(得分:0)
在这种情况下,getMenuInfo()
方法将返回null,因为这些视图没有将任何额外信息附加到菜单。这可能会使您免于ClassCastException
,因为这些视图不是AdapterView的子视图。
让buttonId
成为您的活动的类成员,并从传递到onCreateContextMenu()
方法的视图中检索它。
private int buttonId;
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
buttonId = v.getId();
...
}