簡體   English   中英

更改工具欄操作項的背景色

[英]Change toolbar action item background color

如何在工具欄中更改菜單操作項的背景顏色?

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

    <item
        android:id="@+id/my_action"
        android:icon="@mipmap/icon"
        android:title="@string/title"
        app:showAsAction="always" />
</menu>

然后在我的活動中:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_actions, menu);

    final MenuItem item = menu.findItem(R.id.my_action);

    MenuItemCompat.getActionView(item).setBackgroundColor(ContextCompat.getColor(this, R.color.red));

    return super.onCreateOptionsMenu(menu);

}

這不起作用,因為getActionView始終返回null。

開始了:

public void changeActionMenuItemsBackground(int color) {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    for (int i = 0; i < toolbar.getChildCount(); i++) {
        final View v = toolbar.getChildAt(i);
        if (v instanceof ActionMenuView) {
            v.setBackgroundColor(color);
        }
    }
}

您可以在onCreateOptionsMenu()或更高版本中直接調用它

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    changeActionMenuItemsBackground(Color.BLACK);
    return true;
}

希望對您有幫助

在我的情況下,當setActionView()中有一個自定義actionView時,getActionView()正在工作。

創建一個布局並將其設置為菜單項的操作視圖,如下所示:

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.new_menu, menu);
    MenuItem item = menu.findItem(R.id.my_action);
    View myView = LayoutInflater.from(this).inflate(R.layout.menu_item_layout, null);
    ((ImageView) myView.findViewById(R.id.btnEdit)).setOnClickListener(this);
    item = MenuItemCompat.setActionView(item, myView);
    MenuItemCompat.getActionView(item).setBackgroundColor(ContextCompat.getColor(this, R.color.blue));
    return true;
}

menu_item_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/btnEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/red"
android:minHeight="0dp"
android:minWidth="0dp"
android:src="@drawable/img_edt" />

這樣,您可以在getActionView(item).setBackgroundColor(..)或menu_item_layout.xml文件本身中設置顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM