Android action bar options menu item custom selectable background

You can try setting the android:actionBarItemBackground attribute in styles, like so:

<style name="AppTheme" parent="android:Theme.Material">
    ...
    <item name="android:actionBarItemBackground">?android:selectableItemBackground</item>
</style>

Use one of the following solutions:

Solution 1:

Add <item name="actionButtonStyle">@style/ActionButtonStyle</item> to your base application theme with for exmaple:

<style name="ActionButtonStyle" parent="android:Widget.Material.Button">
            <item name="android:textColor">@android:color/black</item>
            <item name="android:textSize">16sp</item>
            <item name="android:background">@drawable/button_background</item>
</style>

and

button_background

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
            android:drawable="@color/colorAccent"/>
    <item android:state_focused="true"
            android:drawable="@color/colorPrimaryDark"/>
    <item android:drawable="@color/colorPrimary"/>
</selector>

Solution 2:

Use menuItem.setActionView to apply a custom layout to your menu item as follows:

layout_action_cancel (custom menu item layout):

<Button
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancel"
        android:id="@+id/b_action_cancel"
        android:gravity="center"
        android:background="@drawable/button_background">
</Button>

Then in your onCreateOptionsMenu apply the custom Layout to the menu
item:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu, menu);
        LayoutInflater layoutInflater = getLayoutInflater();
        View layout = layoutInflater.inflate(R.layout.layout_action_cancel, null, false);
        menu.getItem(0).setActionView(layout);
        return super.onCreateOptionsMenu(menu);
    }

and in onPrepareOptionsMenu set an OnClick Listener (replacing the
onOptionsItemSelected)

@Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        View layout = menu.getItem(0).getActionView();
        if(layout instanceof Button){
            Button b_action_cancel = layout.findViewById(R.id.b_action_cancel);
            b_action_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //your code
                }
            });
        }
        return super.onPrepareOptionsMenu(menu);
    }

Leave a Comment