Tag Archives: New problems in Android Development

Solution to the problem that the toolbar menu button cannot be clicked

Today, I encountered a bug. I added a menu to the toolbar, but there is no response when I click it. In other words, this button cannot be clicked.

Menu file menu_ toolbar_ announcement_ comment:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_comment"
        android:title="@string/comment"
        android:visible="true"
        app:actionLayout="@layout/menu_provider_number_subscript"
        app:showAsAction="always" />

</menu>

code:

mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_comment:
                        //enable comment
                        showComment();
                        break;
                }
                return true;
            }
        });

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_toolbar_announcement_comment, menu);
        return true;
    }

The setonmenuitemclicklistener method in the code doesn’t work.

I think the reason may be that I use custom layout in menu
app: actionlayout = @ layout/menu_ provider_ number_ subscript"

At this time, you need to write the click event of the menu in oncreateoptionsmenu

The details are as follows:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_toolbar_announcement_comment, menu);
        MenuItem item = menu.findItem(R.id.menu_comment);
        item.getActionView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //enable comment
                showComment();
            }
        });
        return true;
    }