我可以改变一个菜单项的背景颜色在安卓?

如果有人对此有任何解决方案,请让我知道。最后一个选项显然是自定义,但是否有任何方法可以在不自定义的情况下更改文本颜色。


当前回答

如果要为单个菜单项设置颜色,自定义工具栏主题不是正确的解决方案。为了实现这一点,你可以使用android:actionLayout和菜单项的动作视图。

首先为操作视图创建一个XML布局文件。在这个例子中,我们使用一个按钮作为一个动作视图:

menu_button.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/menuButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Done"
        android:textColor="?android:attr/colorAccent"
        style="?android:attr/buttonBarButtonStyle"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

在上面的代码片段中,我们使用android:textColor="?android:attr/colorAccent"自定义按钮文本颜色。

然后在菜单的XML布局文件中,包括app:actionLayout="@layout/menu_button",如下所示:

main_menu.xml

<?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/menuItem"
        android:title=""
        app:actionLayout="@layout/menu_button"
        app:showAsAction="always"/>
</menu>

最后重写oncreateoptionsmmenu()方法在你的活动:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    MenuItem item = menu.findItem(R.id.menuItem);
    Button saveButton = item.getActionView().findViewById(R.id.menuButton);
    saveButton.setOnClickListener(view -> {
        // Do something
    });
    return true;
}

...或片段:

@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater){
    inflater.inflate(R.menu.main_menu, menu);
    MenuItem item = menu.findItem(R.id.menuItem);
    Button saveButton = item.getActionView().findViewById(R.id.menuButton);
    button.setOnClickListener(view -> {
        // Do something
    });
}

有关操作视图的更多细节,请参阅Android开发者指南。

其他回答

Sephy的方法不管用。可以使用上述方法覆盖选项菜单项文本外观,但不能覆盖项或菜单。要做到这一点,基本上有3种方法:

如何更改选项菜单的背景颜色? 写你自己的视图来显示和覆盖onCreateOptionsMenu和onPrepareOptionsMenu来获得你想要的结果。我之所以笼统地说明这一点,是因为您通常可以在这些方法中做任何您想做的事情,但您可能不想调用super()。 从开源SDK复制代码,并自定义您的行为。Activity使用的默认菜单实现将不再适用。

参见第4441期:自定义选项菜单主题了解更多线索。

您可以通过编程方式设置颜色。

private static void setMenuTextColor(final Context context, final Toolbar toolbar, final int menuResId, final int colorRes) {
    toolbar.post(new Runnable() {
        @Override
        public void run() {
            View settingsMenuItem =  toolbar.findViewById(menuResId);
            if (settingsMenuItem instanceof TextView) {
                if (DEBUG) {
                    Log.i(TAG, "setMenuTextColor textview");
                }
                TextView tv = (TextView) settingsMenuItem;
                tv.setTextColor(ContextCompat.getColor(context, colorRes));
            } else { // you can ignore this branch, because usually there is not the situation
                Menu menu = toolbar.getMenu();
                MenuItem item = menu.findItem(menuResId);
                SpannableString s = new SpannableString(item.getTitle());
                s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), 0, s.length(), 0);
                item.setTitle(s);
            }

        }
    });
}

在Kotlin中我写了这些扩展:

fun MenuItem.setTitleColor(color: Int) {
    val hexColor = Integer.toHexString(color).toUpperCase().substring(2)
    val html = "<font color='#$hexColor'>$title</font>"
    this.title = html.parseAsHtml()
}           



@Suppress("DEPRECATION")                                                                        
fun String.parseAsHtml(): Spanned {                                                             
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {                                
        Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)                                         
    } else {                                                                                    
        Html.fromHtml(this)                                                                     
    }                                                                                           
}  

并像这样使用:

menu.findItem(R.id.main_settings).setTitleColor(Color.RED)

最简单的方法为单个工具栏定制菜单颜色,而不是为AppTheme

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay.MenuBlue">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"/>
    </android.support.design.widget.AppBarLayout>

xml上常用的工具栏

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>

自定义工具栏样式

<style name="AppTheme.AppBarOverlay.MenuBlue">
    <item name="actionMenuTextColor">@color/blue</item>
</style>

主题中的一句话:)

<item name="android:actionMenuTextColor">@color/your_color</item>