问题
I use SherlockListActivity, I created ActionBar with one item & its clickListener when i click on it for first time after creating activity, doesn't call onMenuItemClick, but in every click after first click, work with no problem
Why ?
private void BuildTopActionBar() {
BitmapDrawable bg = (BitmapDrawable) getResources().getDrawable(
R.drawable.ic_action_bg);
bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
getSupportActionBar().setBackgroundDrawable(bg);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.getSupportActionBar().setHomeButtonEnabled(true);
this.getSupportActionBar().setTitle("bookmarks");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This is called when the Home (Up) button is pressed in the Action Bar.
finish();
return true;
case add_bookmark_item:
// add
item.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
customAmbilWarnaDialog dialog = new customAmbilWarnaDialog(
BookMarksActivity.this, 0xffffffff,
new OnAmbilWarnaListener() {
public void onCancel(
customAmbilWarnaDialog dialog) {
}
public void onOk(customAmbilWarnaDialog dialog,
int color, String name, int hasName) {
myDbHelper.AddNewBookmark(name,
currentPageNum, color, hasName);
// code
lv.smoothScrollToPosition((lv.getCount() - 1));
}
});
dialog.show();
return true;
}
});
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, add_bookmark_item, 0, "add bookmark")
.setIcon(R.drawable.bookmark_add)
.setShowAsAction(
MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
| MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
回答1:
the reason is that you're calling the item.setOnMenuItemClickListener(new OnMenuItemClickListener() {...
in the onOptionsItemSelected()
method.
This means it will be set the first time you click the menuItem
(and then reset on every click) and the code inside it will only run once you've clicked it at least once.
either call this in onCreateOptionsMenu()
or simply move the code from onMenuItemClick()
to the switch/case
来源:https://stackoverflow.com/questions/14358413/doesnt-call-onmenuitemclick-for-first-time-sherlocklistactivity