Android action bar menu item with actionLayout not working properly

我们两清 提交于 2019-12-03 02:20:12

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 :)

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;
}
Willy Chen

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!