ContextMenu throws a NullPointerException
I'm trying to make a ContextMenu within my InputMethodService.
it gets initiates as
private ContextMenu ContextMenuInfo = null;
then within OnLongClick it has
ContextMenuInfo.setHeaderTitle("hello!");
ContextMenuInfo.add("aaa!");
ContextMenuInfo.add("bbb!"); 开发者_JAVA百科
mInputView.createContextMenu(ContextMenuInfo);
but it throws a NullPointerException. any ideas what might be missing?
Thanks!
edit:
tried with
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Choose an option");
menu.add(0, v.getId(), 0, "Add to favorites");
menu.add(0, v.getId(), 0, "See details");
}
and within the longclick
registerForContextMenu( v );
openContextMenu( v );
but they both give
The method registerForContextMenu(View) is undefined for the type new View.OnLongClickListener(){}
So... you set ContextMenuInfo
as null
, then you try to call methods on it and you get a NullPointerException
. That shouldn't be surprising. You're essentially calling null.setHeaderTitle("hello!");
.
In onCreate()
, have the lines:
Button b = (Button) findViewById(R.id.myButton);
registerForContextMenu(b);
Then, as you have, run these commands in onCreateContextMenu (or, more ideally, inflate the context menu from a resources xml file):
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Choose an option");
menu.add(0, v.getId(), 0, "Add to favorites");
menu.add(0, v.getId(), 0, "See details");
}
You can't call methods on a ContextMenuInfo object (or any object really) without instantiating it first.
Link for creating a context menu for a view.
精彩评论