android – onOptionsItemSelected not getting called when using custom action view-ThrowExceptions

Exception or error:

I set an custom view for one of my actionbar MenuBar like this

    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(, menu);
        ImageView iv = (ImageView)(getLayoutInflater().inflate(R.layout.image_container, null));

but when I tap that menu item in my app, onOptionsItemSelected() does not get called. (I have verified this via setting a breakpoint at the beginning of the method). If I tap the other buttons, in Action bar, onOptionsItemSelected() does get called.

here is the xml code fo rmy custom view:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android=""
    style = "@android:style/Widget.ActionButton"/>

I’ve also tried setting the Action view on the menu xml file :

    <item android:id="@+id/action_filter"
    android:showAsAction="ifRoom" />

Note: I know I can make the image clickable, and manually set an onClickListener for it, but for the sake of learning, I want to get to the bottom of this.

How to solve:

It seems that the underlying code that inflates and draws the action items, doesn’t connect the contents of the custom layout set by setActionView() or by the android:actionLayout="@layout/image_container".

Probably because the layout can be anything, and just a button or image. So I must manually set the onClickListener for the icon. For the purpose of organization, I just call onOptionsItemSelected() from the OnClick method of my icon, but I could just define the action inside the onClick method.

first, declare filterMenuItem in your Activity.

MenuItem filterMenuItem;

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(, menu);
    filterMenuItem = menu.findItem(;

    filterMenuItem.getActionView().setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {


you have to call menu.add() method and implemenet onPreareOptionsmenu instead of oncreateoptionsmenu method. This is my code:

    public boolean onPrepareOptionsMenu(Menu menu) {                

        if(mAlbum.getStatus() == Album.STATUS_VIDEO_AVAILABLE)
            menu.add(0, 0 , 0, getString(R.string.edit_album))
            menu.add(0, 1 , 0, getString(R.string.delete_album))
            menu.add(0, 2 , 0, getString(R.string.download_video))
            menu.add(0, 3 , 0, getString(R.string.upload_to_ambivo))
            menu.add(0, 4 , 0, getString(R.string.upload_to_facebook))
            menu.add(0, 5 , 0, getString(R.string.upload_to_youtube))

            MenuInflater inflater = getMenuInflater();
            inflater.inflate(, menu);
            if(mAlbum.getAlbumType() == Album.COMPOSITE_VIDEOS)

        return true;

Leave a Reply

Your email address will not be published. Required fields are marked *