Hi I am developing an Android application. In my application I am using Sherlock action. I\'ve defined few menu items in action-bar like in following manner
<
Refer to the answer
If there is a button in the action layout, in order to get the callback from menu item, don't forget to set the button
android:clickable="false"
Full working code
<item
android:title="search"
android:id="@+id/mSearch"
app:actionLayout="@layout/my_custom_menu_item"
android:orderInCategory="100"
app:showAsAction="always"/>
Code:
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu); MenuItem item = menu.findItem(R.id.mSearch);
ImageView iv= (ImageView) item.getActionView().findViewById(R.id.search_1);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "clicked", Toast.LENGTH_SHORT).show();
}
});
return true;
}
Try this code in your activity.
Be sure to properly set your
R.menu.menuidentifier
R.id.menuitemidentifier
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.actionbarhelpmenu, menu);
final Menu m = menu;
final MenuItem item = menu.findItem(R.id.ActionConnection);
item.getActionView().setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
m.performIdentifierAction(item.getItemId(), 0);
}
});
return true;
}
Accepted answer didn't work for me. My submenu behaved different on different devices. On Motorola Moto X it was like this:
You can see that sub-menu is in wrong position (I clicked on bubble icon on the right of ActionBar).
So at the end I came up with different solution: use PopupMenu instead. Code looks like this:
@Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_fragment_chat, menu);
final MenuItem item = menu.findItem(R.id.menu_item_actionbar_avatar);
MenuItemCompat.getActionView(item).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showProfileMenuPopup(v);
}
});
}
public void showProfileMenuPopup(View v) {
PopupMenu popup = new PopupMenu(getActivity(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_avatar_actions, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
return false;
}
});
popup.show();
}
And it worked :)