204

我可以更改 Android 中菜单项的背景颜色吗?

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

4

29 回答 29

364

主题中的一条简单线:)

<item name="android:actionMenuTextColor">@color/your_color</item>
于 2014-09-08T19:27:15.500 回答
132

似乎一个

  <item name="android:itemTextAppearance">@style/myCustomMenuTextAppearance</item>

在我的主题和

   <style name="myCustomMenuTextAppearance" parent="@android:style/TextAppearance.Widget.IconMenu.Item">
        <item name="android:textColor">@android:color/primary_text_dark</item>
    </style>

在styles.xml 中更改列表项的样式,但不更改菜单项。

于 2011-04-04T12:51:25.047 回答
103

MenuItem您可以通过使用SpannableString而不是轻松更改文本的颜色String

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.your_menu, menu);

    int positionOfMenuItem = 0; // or whatever...
    MenuItem item = menu.getItem(positionOfMenuItem);
    SpannableString s = new SpannableString("My red MenuItem");
    s.setSpan(new ForegroundColorSpan(Color.RED), 0, s.length(), 0);
    item.setTitle(s);
}
于 2013-09-25T15:03:57.440 回答
75

如果您使用的是带有主题的新工具栏,Theme.AppCompat.Light.NoActionBar您可以通过以下方式对其进行样式设置。

 <style name="ToolbarTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:textColorPrimary">@color/my_color1</item>
    <item name="android:textColorSecondary">@color/my_color2</item>
    <item name="android:textColor">@color/my_color3</item>
 </style>`

根据我得到的结果,
android:textColorPrimary是显示活动名称的文本颜色,它是工具栏的主要文本。

android:textColorSecondary是字幕和更多选项(3 点)按钮的文本颜色。(是的,它根据这个属性改变了颜色!)

android:textColor是所有其他文本的颜色,包括菜单。

最后将主题设置为工具栏

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:theme="@style/ToolbarTheme"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"/>
于 2015-03-28T10:48:58.970 回答
41

我以这样的方式进行编程:

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.changeip_card_menu, menu); 
    for(int i = 0; i < menu.size(); i++) {
        MenuItem item = menu.getItem(i);
        SpannableString spanString = new SpannableString(menu.getItem(i).getTitle().toString());
        spanString.setSpan(new ForegroundColorSpan(Color.BLACK), 0,     spanString.length(), 0); //fix the color to white
        item.setTitle(spanString);
    }
    return true;
}
于 2015-09-15T12:28:01.883 回答
32

如果您使用的是菜单,<android.support.design.widget.NavigationView />那么只需添加以下行NavigationView

app:itemTextColor="your color"

也可用于图标的 colorTint,它也会覆盖您图标的颜色。为此,您必须添加以下行:

app:itemIconTint="your color"

例子:

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"

        app:itemTextColor="@color/color_white"
        app:itemIconTint="@color/color_white"

        android:background="@color/colorPrimary"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"/>

希望它会帮助你。

于 2016-02-02T13:16:50.200 回答
17

正如您在这个问题中看到的那样,您应该:

<item name="android:textColorPrimary">yourColor</item>

上面的代码更改了 API >= v21 的菜单操作项的文本颜色。

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

以上是 API < v21 的代码

于 2017-04-18T10:46:15.283 回答
11

在 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)
于 2018-04-03T12:01:41.880 回答
10

为单个工具栏而不是 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>

styles.xml 上的常用工具栏

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

我们的自定义工具栏样式

<style name="AppTheme.AppBarOverlay.MenuBlue">
    <item name="actionMenuTextColor">@color/blue</item>
</style>
于 2017-01-13T14:49:41.930 回答
10

当菜单项膨胀时,我使用 html 标记更改单个项的文本颜色。希望它会有所帮助。

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    menu.findItem(R.id.main_settings).setTitle(Html.fromHtml("<font color='#ff3824'>Settings</font>"));
    return true;
}
于 2015-10-28T02:01:29.130 回答
8

我正在使用材料设计,当工具栏在小屏幕上时,单击更多选项会显示一个空白的白色下拉框。为了解决这个问题,我认为将其添加到主 AppTheme:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:itemTextAppearance">@style/menuItem</item>
</style>

然后创建一个样式,在其中将菜单项的 textColor 设置为所需的颜色。

<style name="menuItem" parent="Widget.AppCompat.TextView.SpinnerItem">
    <item name="android:textColor">@color/black</item>
</style>

父母的名字Widget.AppCompat.TextView.SpinnerItem我认为这并不重要,它应该仍然有效。

于 2020-08-06T08:22:25.183 回答
7

更改菜单项文本颜色使用下面的代码

<style name="AppToolbar" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:itemTextAppearance">@style/menu_item_color</item>
</style>

在哪里

<style name="menu_item_color">
<item name="android:textColor">@color/app_font_color</item>
</style>
于 2018-08-03T06:23:45.427 回答
6

可以自定义 android 中的选项菜单以设置背景或更改文本外观。无法使用主题和样式更改菜单中的背景和文本颜色。android 源代码 (data\res\layout\icon_menu_item_layout.xml) 使用“com.android.internal.view.menu.IconMenuItem”类的自定义项来进行菜单布局。我们可以在上面的类中进行修改来自定义菜单。为了达到同样的效果,使用 LayoutInflater 工厂类并设置视图的背景和文本颜色。


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
    getLayoutInflater().setFactory(new Factory() {
        @Override
        public View onCreateView(String name, Context context, AttributeSet attrs) {
            if (name .equalsIgnoreCase(“com.android.internal.view.menu.IconMenuItemView”)) {
                try{
                    LayoutInflater f = getLayoutInflater();
                    final View view = f.createView(name, null, attrs);
                    new Handler().post(new Runnable() {
                        public void run() {
                            // set the background drawable
                            view .setBackgroundResource(R.drawable.my_ac_menu_background);

                            // set the text color
                            ((TextView) view).setTextColor(Color.WHITE);
                        }
                    });
                    return view;
                } catch (InflateException e) {
                    } catch (ClassNotFoundException e) {}
            }
            return null;
        }
    });
    return super.onCreateOptionsMenu(menu);
}


于 2011-06-02T05:49:43.927 回答
6

感谢您的代码示例。我必须修改它才能使用上下文菜单。这是我的解决方案。

    static final Class<?>[] constructorSignature = new Class[] {Context.class, AttributeSet.class};

class MenuColorFix implements LayoutInflater.Factory {
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        if (name.equalsIgnoreCase("com.android.internal.view.menu.ListMenuItemView")) {
            try {
                Class<? extends ViewGroup> clazz = context.getClassLoader().loadClass(name).asSubclass(ViewGroup.class);
                Constructor<? extends ViewGroup> constructor = clazz.getConstructor(constructorSignature);
                final ViewGroup view = constructor.newInstance(new Object[]{context,attrs});

                new Handler().post(new Runnable() {
                    public void run() {
                        try {
                            view.setBackgroundColor(Color.BLACK);
                            List<View> children = getAllChildren(view);
                            for(int i = 0; i< children.size(); i++) {
                                View child = children.get(i);
                                if ( child instanceof TextView ) {
                                    ((TextView)child).setTextColor(Color.WHITE);
                                }
                            }
                        }
                        catch (Exception e) {
                            Log.i(TAG, "Caught Exception!",e);
                        }

                    }
                });
                return view;
            }
            catch (Exception e) {
                Log.i(TAG, "Caught Exception!",e);
            }
        }
        return null;
    }       
}

public List<View> getAllChildren(ViewGroup vg) {
    ArrayList<View> result = new ArrayList<View>();
    for ( int i = 0; i < vg.getChildCount(); i++ ) {
        View child = vg.getChildAt(i);
        if ( child instanceof ViewGroup) {
            result.addAll(getAllChildren((ViewGroup)child));
        }
        else {
            result.add(child);
        }
    }
    return result;
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    LayoutInflater lInflater = getLayoutInflater();
    if ( lInflater.getFactory() == null ) {
        lInflater.setFactory(new MenuColorFix());
    }
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.myMenu, menu);
}

对我来说,这适用于 Android 1.6、2.03 和 4.03。

于 2012-05-22T12:20:58.127 回答
6

简短的回答是肯定的。幸运的你!
为此,您需要覆盖 Android 默认样式的一些样式:

首先看一下Android 中主题的定义:

<style name="Theme.IconMenu">
<!-- Menu/item attributes -->
<item name="android:itemTextAppearance">@android:style/TextAppearance.Widget.IconMenu.Item</item>
<item name="android:itemBackground">@android:drawable/menu_selector</item>
<item name="android:itemIconDisabledAlpha">?android:attr/disabledAlpha</item>
<item name="android:horizontalDivider">@android:drawable/divider_horizontal_bright</item>
<item name="android:verticalDivider">@android:drawable/divider_vertical_bright</item>
<item name="android:windowAnimationStyle">@android:style/Animation.OptionsPanel</item>
<item name="android:moreIcon">@android:drawable/ic_menu_more</item>
<item name="android:background">@null</item>
</style>

因此,菜单中文本的外观@android:style/TextAppearance.Widget.IconMenu.Item
现在,在样式的定义中:

<style name="TextAppearance.Widget.IconMenu.Item" parent="TextAppearance.Small">
<item name="android:textColor">?textColorPrimaryInverse</item>
</style>

所以现在我们有了问题颜色的名称,如果你查看系统资源的颜色文件夹:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/bright_foreground_light_disabled" /> 
<item android:state_window_focused="false" android:color="@android:color/bright_foreground_light" /> 
<item android:state_pressed="true" android:color="@android:color/bright_foreground_light" /> 
<item android:state_selected="true" android:color="@android:color/bright_foreground_light" /> 
<item android:color="@android:color/bright_foreground_light" /> 
<!--  not selected --> 
</selector>

最后,这是您需要做的:

覆盖“TextAppearance.Widget.IconMenu.Item”并创建自己的样式。然后将其链接到您自己的选择器以使其成为您想要的方式。希望这对您有所帮助。祝你好运!

于 2010-08-19T09:10:52.413 回答
5

我发现它尤里卡!

在您的应用主题中:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/ActionBarTheme</item>
    <!-- backward compatibility -->          
    <item name="actionBarStyle">@style/ActionBarTheme</item>        
</style>

这是您的操作栏主题:

<style name="ActionBarTheme" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
   <item name="android:background">@color/actionbar_bg_color</item>
   <item name="popupTheme">@style/ActionBarPopupTheme</item
   <!-- backward compatibility -->
   <item name="background">@color/actionbar_bg_color</item>
</style>

这是您的弹出主题:

 <style name="ActionBarPopupTheme">
    <item name="android:textColor">@color/menu_text_color</item>
    <item name="android:background">@color/menu_bg_color</item>
 </style>

干杯;)

于 2015-07-06T23:24:08.833 回答
4

感谢 max.musterman,这是我在第 22 级工作的解决方案:

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    MenuItem searchMenuItem = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) searchMenuItem.getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(this);
    setMenuTextColor(menu, R.id.displaySummary, R.string.show_summary);
    setMenuTextColor(menu, R.id.about, R.string.text_about);
    setMenuTextColor(menu, R.id.importExport, R.string.import_export);
    setMenuTextColor(menu, R.id.preferences, R.string.settings);
    return true;
}

private void setMenuTextColor(Menu menu, int menuResource, int menuTextResource) {
    MenuItem item = menu.findItem(menuResource);
    SpannableString s = new SpannableString(getString(menuTextResource));
    s.setSpan(new ForegroundColorSpan(Color.BLACK), 0, s.length(), 0);
    item.setTitle(s);
}

硬编码Color.BLACK可以成为该setMenuTextColor方法的附加参数。另外,我只将它用于菜单项android:showAsAction="never"

于 2016-11-01T19:10:07.333 回答
3

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

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);
            }

        }
    });
}
于 2017-05-13T10:48:43.623 回答
3

如果您想为单个菜单项设置颜色,自定义工具栏主题不是正确的解决方案。为此,您可以使用 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>

最后覆盖onCreateOptionsMenu()活动中的方法:

@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 开发人员指南

于 2019-09-04T09:12:13.647 回答
3

只需将其添加到您的主题中

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:itemTextAppearance">@style/AppTheme.ItemTextStyle</item>
</style>

<style name="AppTheme.ItemTextStyle" parent="@android:style/TextAppearance.Widget.IconMenu.Item">
        <item name="android:textColor">@color/orange_500</item>
</style>

在 API 21 上测试

于 2016-09-09T03:12:50.467 回答
3

将此添加到我的 styles.xml 中对我有用

<item name="android:textColorPrimary">?android:attr/textColorPrimaryInverse</item>
于 2018-07-18T22:13:03.290 回答
2
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.search, menu);


    MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
    SearchView searchView = (SearchView) myActionMenuItem.getActionView();

    EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
    searchEditText.setTextColor(Color.WHITE); //You color here
于 2017-03-09T17:27:24.197 回答
2

我的情况是在选项菜单中设置文本颜色(按下菜单按钮时显示主应用程序菜单)。

使用appcompat-v7-27.0.2库在API 16中测试,适用于AndroidManifest.xml中的应用程序和主题。AppCompatActivityMainActivityAppCompat

样式.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  <item name="actionBarPopupTheme">@style/PopupTheme</item>
</style>

<style name="PopupTheme" parent="@style/ThemeOverlay.AppCompat.Light">
  <item name="android:textColorSecondary">#f00</item>
</style>

不知道这是否textColorSecondary会影响其他元素,但它控制菜单文本颜色。


我搜索了一些关于该主题的示例,但所有现成的片段都不起作用。

所以我想用appcompat-v7库的源代码(特别是.aar包的res文件夹)来研究它。

虽然在我的情况下,我使用 Eclipse 与爆炸的 .aar依赖项。所以我可以更改默认样式并检查结果。不知道如何分解库以直接与GradleAndroid Studio一起使用。它值得另一个调查。

所以我的目的是找到res/values/values.xml文件中的哪种颜色用于菜单文本(我几乎确定颜色在那里)。

  1. 我打开该文件,然后复制所有颜色,将它们放在默认颜色下方以覆盖它们并为所有颜色分配#f00值。
  2. 启动应用程序。
  3. 许多元素具有红色背景或文本颜色。还有菜单项。这正是我所需要的。
  4. 通过 5-10 行的块删除我添加的颜色,我以secondary_text_default_material_light颜色项目结束。
  5. 在res文件夹中的文件中搜索该名称(或者在res/colors中更好)我发现在color/abc_secondary_text_material_light.xml文件中只出现了一次(我使用 Sublime Text 进行这些操作,因此更容易找到我需要的东西)。
  6. 返回values.xml找到 8 种用法@color/abc_secondary_text_material_light
  7. 这是一个Light主题,所以在 2 个主题中剩下 4 个:Base.ThemeOverlay.AppCompat.LightPlatform.AppCompat.Light.
  8. 第一个主题是第二个主题的子主题,因此该颜色资源只有 2 个属性:android:textColorSecondary并且android:textColorTertiaryBase.ThemeOverlay.AppCompat.Light.
  9. 直接在values.xml中更改它们的值并运行应用程序我发现最终正确的属性是android:textColorSecondary.
  10. 接下来我需要一个主题或其他属性,以便我可以在我的应用程序的style.xml中更改它(因为我的主题有作为父级Theme.AppCompat.Light而不是ThemeOverlay.AppCompat.Light)。
  11. 我在同一个文件中搜索Base.ThemeOverlay.AppCompat.Light. 它有一个孩子ThemeOverlay.AppCompat.Light
  12. 搜索ThemeOverlay.AppCompat.Light我发现它在Base.Theme.AppCompat.Light.DarkActionBar主题中作为actionBarPopupTheme属性值的用法。
  13. 我的应用程序主题Theme.AppCompat.Light.DarkActionBar是 found 的子主题,Base.Theme.AppCompat.Light.DarkActionBar因此我可以在我的styles.xml中使用该属性而不会出现问题。
  14. 正如在上面的示例代码中看到的那样,我从提到的创建了一个子主题ThemeOverlay.AppCompat.Light并更改了android:textColorSecondary属性。

https://i.imgur.com/LNfKdzC.png

于 2018-01-15T17:04:34.980 回答
1

试试这个代码....

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

        getLayoutInflater().setFactory(new Factory() {
            @Override
            public View onCreateView(String name, Context context,
                    AttributeSet attrs) {

                if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {
                    try {
                        LayoutInflater f = getLayoutInflater();
                        final View view = f.createView(name, null, attrs);

                        new Handler().post(new Runnable() {
                            public void run() {

                                // set the background drawable
                                 view.setBackgroundResource(R.drawable.my_ac_menu_background);

                                // set the text color
                                ((TextView) view).setTextColor(Color.WHITE);
                            }
                        });
                        return view;
                    } catch (InflateException e) {
                    } catch (ClassNotFoundException e) {
                    }
                }
                return null;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }
于 2012-08-19T13:23:57.483 回答
1

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

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

有关更多线索,请参阅问题 4441:自定义选项菜单主题

于 2010-10-17T09:12:13.517 回答
0

这是您可以使用颜色为特定菜单项着色的方法,适用于所有 API 级别:

public static void setToolbarMenuItemTextColor(final Toolbar toolbar,
                                               final @ColorRes int color,
                                               @IdRes final int resId) {
    if (toolbar != null) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            final View view = toolbar.getChildAt(i);
            if (view instanceof ActionMenuView) {
                final ActionMenuView actionMenuView = (ActionMenuView) view;
                // view children are accessible only after layout-ing
                actionMenuView.post(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 0; j < actionMenuView.getChildCount(); j++) {
                            final View innerView = actionMenuView.getChildAt(j);
                            if (innerView instanceof ActionMenuItemView) {
                                final ActionMenuItemView itemView = (ActionMenuItemView) innerView;
                                if (resId == itemView.getId()) {
                                    itemView.setTextColor(ContextCompat.getColor(toolbar.getContext(), color));
                                }
                            }
                        }
                    }
                });
            }
        }
    }
}

通过这样做,您会失去背景选择器效果,因此这里是将自定义背景选择器应用于所有菜单项子项的代码。

public static void setToolbarMenuItemsBackgroundSelector(final Context context,
                                                         final Toolbar toolbar) {
    if (toolbar != null) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            final View view = toolbar.getChildAt(i);
            if (view instanceof ImageButton) {
                // left toolbar icon (navigation, hamburger, ...)
                UiHelper.setViewBackgroundSelector(context, view);
            } else if (view instanceof ActionMenuView) {
                final ActionMenuView actionMenuView = (ActionMenuView) view;

                // view children are accessible only after layout-ing
                actionMenuView.post(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 0; j < actionMenuView.getChildCount(); j++) {
                            final View innerView = actionMenuView.getChildAt(j);
                            if (innerView instanceof ActionMenuItemView) {
                                // text item views
                                final ActionMenuItemView itemView = (ActionMenuItemView) innerView;
                                UiHelper.setViewBackgroundSelector(context, itemView);

                                // icon item views
                                for (int k = 0; k < itemView.getCompoundDrawables().length; k++) {
                                    if (itemView.getCompoundDrawables()[k] != null) {
                                        UiHelper.setViewBackgroundSelector(context, itemView);
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
    }
}

这里也是辅助函数:

public static void setViewBackgroundSelector(@NonNull Context context, @NonNull View itemView) {
    int[] attrs = new int[]{R.attr.selectableItemBackgroundBorderless};
    TypedArray ta = context.obtainStyledAttributes(attrs);
    Drawable drawable = ta.getDrawable(0);
    ta.recycle();

    ViewCompat.setBackground(itemView, drawable);
}
于 2017-02-19T15:22:19.840 回答
0

要更改文本颜色,您可以为 MenuItem 设置自定义视图,然后您可以定义文本的颜色。

示例代码:MenuItem.setActionView()

于 2017-08-24T09:56:07.333 回答
0

Add textColor as below

<style name="MyTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light">
    <item name="android:textColor">@color/radio_color_gray</item>
</style>

and use it in Toolbar in xml file

<androidx.appcompat.widget.Toolbar
     android:id="@+id/toolbar"
     android:layout_width="match_parent"
     android:layout_height="?attr/actionBarSize"
     app:popupTheme="@style/MyTheme.PopupOverlay" /> 
于 2021-09-02T06:19:27.007 回答
-4

只需转到值 - 样式和内部样式并输入您的颜色

于 2020-09-30T13:30:35.220 回答