Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onOptionsItemSelected not getting called when using custom action view

Tags:

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.loop_thread, menu);
        ImageView iv = (ImageView)(getLayoutInflater().inflate(R.layout.image_container, null));
        menu.findItem(R.id.action_filter).setActionView(iv);
        ...

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="http://schemas.android.com/apk/res/android"
    android:id="@+id/ibtnFilterMenu"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/darker_gray"
    android:src="@drawable/btn_action_down_arrow"
    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:title="@string/filter_options"
    android:actionLayout="@layout/image_container"
    android:orderInCategory="100"
    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.

like image 751
Siavash Avatar asked Oct 02 '14 22:10

Siavash


1 Answers

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(R.menu.loop_thread, menu);
    filterMenuItem = menu.findItem(R.id.action_filter);

    filterMenuItem.getActionView().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainActivity.this.onOptionsItemSelected(filterMenuItem);
    }
});
like image 188
Siavash Avatar answered Sep 28 '22 08:09

Siavash