如何在Android中改变菜单项的文本颜色?

时间:2023-01-16 12:38:38

Can I change the background color of a Menu item in Android?

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

Please let me know if anyone have any solution to this. The last option will be obviously to customize it but is there any way for changing the text color without customizing it.

如果有人有什么办法,请告诉我。最后一个选项显然是自定义它,但是有没有办法在不自定义的情况下更改文本颜色。

23 个解决方案

#1


249  

One simple line in your theme :)

在你的主题中有一句简单的话:

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

#2


85  

It seems that an

似乎有一个

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

in my theme and

在我的主题和

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

in styles.xml change the style of list-items but not menu items.

在风格。xml改变列表项的样式,而不是菜单项。

#3


59  

You can change the color of the MenuItem text easily by using SpannableString instead of String.

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

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

#4


38  

If you are using the new Toolbar, with the theme Theme.AppCompat.Light.NoActionBar, you can style it in the following way.

如果您正在使用新的工具栏,请使用主题主题. 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>`

According to the results I got,
android:textColorPrimary is the text color displaying the name of your activity, which is the primary text of the toolbar.

android:textColorSecondary is the text color for subtitle and more options (3 dot) button. (Yes, it changed its color according to this property!)

android:textColor is the color for all other text including the menu.

Finally set the theme to the Toolbar

根据我得到的结果,android:textColorPrimary是显示活动名称的文本颜色,是工具栏的主文本。textColorSecondary是字幕和更多选项(3点)按钮的文本颜色。(是的,它根据这个属性改变了颜色!)最后将主题设置为工具栏

<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"/>

#5


20  

If you are using menu as <android.support.design.widget.NavigationView /> then just add below line in NavigationView :

如果您使用菜单作为 ,那么只需在NavigationView中添加以下行:

app:itemTextColor="your color"

Also available colorTint for icon, it will override color for your icon as well. For that you have to add below line:

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

app:itemIconTint="your color"

Example:

例子:

<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"/>

Hope it will help you.

希望它能对你有所帮助。

#6


12  

as you can see in this question you should:

正如你在这个问题中看到的,你应该:

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

Above code changes the text color of the menu action items for API >= v21.

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

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

Above is the code for API < v21

以上是API < v21的代码。

#7


12  

I went about it programmatically like this:

我以编程的方式进行

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

#8


6  

The short answer is YES. lucky you!
To do so, you need to override some styles of the Android default styles :

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

First, look at the definition of the themes in 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>

So, the appearance of the text in the menu is in @android:style/TextAppearance.Widget.IconMenu.Item
Now, in the definition of the styles :

因此,菜单中的文本的外观是@android:style/TextAppearance.Widget.IconMenu。项目现在,在风格的定义中:

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

So now we have the name of the color in question, if you look in the color folder of the resources of the system :

现在我们有了要讨论的颜色的名称,如果你查看系统资源的颜色文件夹:

<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>

Finally, here is what you need to do :

最后,你需要做的是:

Override "TextAppearance.Widget.IconMenu.Item" and create your own style. Then link it to your own selector to make it the way you want. Hope this helps you. Good luck!

TextAppearance.Widget.IconMenu覆盖”。创造你自己的风格。然后将它链接到您自己的选择器,使其成为您想要的方式。希望这能帮助你。好运!

#9


6  

Options menu in android can be customized to set the background or change the text appearance. The background and text color in the menu couldn’t be changed using themes and styles. The android source code (data\res\layout\icon_menu_item_layout.xml)uses a custom item of class “com.android.internal.view.menu.IconMenuItem”View for the menu layout. We can make changes in the above class to customize the menu. To achieve the same, use LayoutInflater factory class and set the background and text color for the view.

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


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


#10


6  

Thanks for the code example. I had to modify it go get it to work with a context menu. This is my solution.

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

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

For me this works with Android 1.6, 2.03 and 4.03.

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

#11


5  

I used the html tag to change a single item's text colour when the menu item is inflated. Hope it would be helpful.

我使用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;
}

#12


4  

i found it Eureka !!

我找到了,尤利卡!!

in your app theme:

在你的应用程序主题:

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

here is your action bar theme:

这是你的动作酒吧主题:

<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>

and here is your popup theme:

这是你的弹出式主题:

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

Cheers ;)

干杯,)

#13


3  

SIMPLEST way to make custom menu color for single toolbar, not for AppTheme

最简单的方法是为单个工具栏创建自定义菜单颜色,而不是为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>

usual toolbar on styles.xml

常用工具栏上styles.xml

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

our custom toolbar style

我们的自定义工具栏风格

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

#14


2  

Thanks to max.musterman, this is the solution I got to work in level 22:

多亏了马克斯。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);
}

The hardcoded Color.BLACK could become an additional parameter to the setMenuTextColor method. Also, I only used this for menu items which were android:showAsAction="never".

硬编码的颜色。黑色可以成为setMenuTextColor方法的附加参数。另外,我只在菜单项中使用了android:showAsAction="never"。

#15


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

#16


1  

Sephy's solution doesn't work. It's possible to override the options menu item text appearance using the method described above, but not the item or menu. To do that there are essentially 3 ways:

Sephy的解决方案是行不通的。可以使用上面描述的方法覆盖选项菜单项文本外观,但不能覆盖项或菜单。要做到这一点,基本上有三种方法:

  1. How to change the background color of the options menu?
  2. 如何更改选项菜单的背景色?
  3. Write your own view to display and override onCreateOptionsMenu and onPrepareOptionsMenu to get the results you want. I state this generally because you can generally do whatever you want in these methods, but you probably won't want to call into super().
  4. 编写自己的视图来显示和覆盖onCreateOptionsMenu和onPrepareOptionsMenu,以得到您想要的结果。我之所以这样描述,是因为您通常可以在这些方法中执行您想要的任何操作,但是您可能不希望调用super()。
  5. Copy code from the open-source SDK and customize for your behavior. The default menu implementation used by Activity will no longer apply.
  6. 从开源SDK中复制代码并为您的行为定制。活动使用的默认菜单实现将不再适用。

See Issue 4441: Custom Options Menu Theme for more clues.

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

#17


1  

try this code....

试试这个代码....

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

#18


1  

Simply add this to your theme

简单地把它添加到你的主题中

<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>

Tested on API 21

测试API 21

#19


1  

You can set color programmatically.

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

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

        }
    });
}

#20


1  

My situation was settings text color in the options menu (main app menu showed on menu button press).

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

Tested in API 16 with appcompat-v7-27.0.2 library, AppCompatActivity for MainActivity and AppCompat theme for the application in AndroidManifest.xml.

在API 16中使用AppCompat -v7-27.0.2库、主活动的AppCompatActivity和AndroidManifest.xml应用程序的AppCompat主题进行测试。

styles.xml:

styles.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>

Don't know if that textColorSecondary affects other elements but it controls the menu text color.

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


I searched some examples on the topic but all ready-to-use snippets didn't work.

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

So I wanted to investigate it with the source code for the appcompat-v7 library (specifically with the res folder of the .aar package).

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

Though in my case I used Eclipse with exploded .aar dependencies. So I could change the default styles and check the results. Don't know how to explode the libraries to use with Gradle or Android Studio directly. It deserves another thread of investigation.

虽然在我的例子中我使用了Eclipse和爆炸性的。aar依赖项。所以我可以改变默认样式并检查结果。不知道如何将库与Gradle或Android Studio直接使用。它值得进一步研究。

So my purpose was so find which color in the res/values/values.xml file is used for the menu text (I was almost sure the color was there).

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

  1. I opened that file, then duplicated all colors, put them below the default ones to override them and assigned #f00 value to all of them.
  2. 我打开了那个文件,然后复制了所有的颜色,把它们放在默认的颜色下面以覆盖它们,并将#f00值分配给所有的颜色。
  3. Start the app.
  4. 启动应用程序。
  5. Many elements had red background or text color. And the menu items too. That was what I needed.
  6. 许多元素都有红色的背景或文本颜色。还有菜单项目。这正是我所需要的。
  7. Removing my added colors by blocks of 5-10 lines I ended with the secondary_text_default_material_light color item.
  8. 用5-10行代码块删除添加的颜色,最后使用secondary_text_default_material_light颜色项。
  9. Searching that name in the files within the res folder (or better within res/colors) I found only one occurrence in the color/abc_secondary_text_material_light.xml file (I used Sublime Text for these operations so it's easier to find thing I need).
  10. 在res文件夹(或者在res/colors中)的文件中搜索该名称,我发现颜色/abc_secondary_text_material_light中只有一个名称出现。xml文件(我对这些操作使用了崇高的文本,以便更容易找到我需要的东西)。
  11. Back to the values.xml 8 usages were found for the @color/abc_secondary_text_material_light.
  12. 回值。可以找到@color/abc_secondary_text_material_light的xml 8用法。
  13. It was a Light theme so 4 left in 2 themes: Base.ThemeOverlay.AppCompat.Light and Platform.AppCompat.Light.
  14. 这是一个轻主题,所以4有两个主题:Base.ThemeOverlay.AppCompat。光和Platform.AppCompat.Light。
  15. The first theme was a child of the second one so there were only 2 attributes with that color resource: android:textColorSecondary and android:textColorTertiaryin the Base.ThemeOverlay.AppCompat.Light.
  16. 第一个主题是第二个主题的孩子,所以这个颜色资源只有两个属性:android:textColorSecondary和android: textcolortriaryin The Base.ThemeOverlay.AppCompat.Light。
  17. Changing their values directly in the values.xml and running the app I found that the final correct attribute was android:textColorSecondary.
  18. 在值中直接改变它们的值。我发现最终正确的属性是android:textColorSecondary。
  19. Next I needed a theme or another attribute so I could change it in my app's style.xml (because my theme had as the parent the Theme.AppCompat.Light and not the ThemeOverlay.AppCompat.Light).
  20. 接下来我需要一个主题或另一个属性,这样我就可以在我的应用中改变它的样式。xml(因为我的主题是父类。appcompat。轻,而不是覆盖层。appcompat .轻)。
  21. I searched in the same file for the Base.ThemeOverlay.AppCompat.Light. It had a child ThemeOverlay.AppCompat.Light.
  22. 我在同一个文件中搜索Base.ThemeOverlay.AppCompat.Light。上面有个孩子,appcompat, light。
  23. Searching for the ThemeOverlay.AppCompat.Light I found its usage in the Base.Theme.AppCompat.Light.DarkActionBar theme as the actionBarPopupTheme attribute value.
  24. 寻找ThemeOverlay.AppCompat。我在地下室找到了它的用法。将DarkActionBar主题作为actionBarPopupTheme属性值。
  25. My app's theme Theme.AppCompat.Light.DarkActionBar was a child of the found Base.Theme.AppCompat.Light.DarkActionBar so I could use that attribute in my styles.xml without problems.
  26. 我的应用程序主题Theme.AppCompat.Light。DarkActionBar是一个被发现的Base.Theme.AppCompat.Light的孩子。我可以在样式中使用这个属性。xml没有问题。
  27. As it's seen in the example code above I created a child theme from the mentioned ThemeOverlay.AppCompat.Light and changed the android:textColorSecondary attribute.
  28. 正如上面的示例代码所示,我从上面提到的ThemeOverlay.AppCompat创建了一个子主题。修改了android:textColorSecondary属性。

如何在Android中改变菜单项的文本颜色?

#21


0  

This is how you can color a specific menu item with color, works for all API levels:

这就是如何用颜色为特定的菜单项着色的方法,适用于所有的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));
                                }
                            }
                        }
                    }
                });
            }
        }
    }
}

By doing that you loose the background selector effect, so here is the code to apply a custom background selector to all of the menu item children.

通过这样做,您将失去背景选择器效果,因此下面的代码将应用自定义背景选择器到所有的菜单项子元素。

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

Here is the helper function also:

下面是助手函数:

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

#22


0  

For changing the text color, you can just set a custom view for the MenuItem, and then you can define the color for the text.

要更改文本颜色,只需为MenuItem设置一个自定义视图,然后可以为文本定义颜色。

Sample Code : MenuItem.setActionView()

示例代码:MenuItem.setActionView()

#23


0  

in Kotlin I wrote these extensions:

在Kotlin,我写了这些扩展:

fun MenuItem.setTitleColor(color: Int) {                                                        
    val hexColor = Integer.toHexString(color).toUpperCase().substring(2)                        
    val html = "<font color='#" + hexColor + "'>" + this.title.toString() + "</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)                                                                     
    }                                                                                           
}  

and used like this:

和使用:

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

#1


249  

One simple line in your theme :)

在你的主题中有一句简单的话:

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

#2


85  

It seems that an

似乎有一个

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

in my theme and

在我的主题和

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

in styles.xml change the style of list-items but not menu items.

在风格。xml改变列表项的样式,而不是菜单项。

#3


59  

You can change the color of the MenuItem text easily by using SpannableString instead of String.

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

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

#4


38  

If you are using the new Toolbar, with the theme Theme.AppCompat.Light.NoActionBar, you can style it in the following way.

如果您正在使用新的工具栏,请使用主题主题. 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>`

According to the results I got,
android:textColorPrimary is the text color displaying the name of your activity, which is the primary text of the toolbar.

android:textColorSecondary is the text color for subtitle and more options (3 dot) button. (Yes, it changed its color according to this property!)

android:textColor is the color for all other text including the menu.

Finally set the theme to the Toolbar

根据我得到的结果,android:textColorPrimary是显示活动名称的文本颜色,是工具栏的主文本。textColorSecondary是字幕和更多选项(3点)按钮的文本颜色。(是的,它根据这个属性改变了颜色!)最后将主题设置为工具栏

<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"/>

#5


20  

If you are using menu as <android.support.design.widget.NavigationView /> then just add below line in NavigationView :

如果您使用菜单作为 ,那么只需在NavigationView中添加以下行:

app:itemTextColor="your color"

Also available colorTint for icon, it will override color for your icon as well. For that you have to add below line:

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

app:itemIconTint="your color"

Example:

例子:

<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"/>

Hope it will help you.

希望它能对你有所帮助。

#6


12  

as you can see in this question you should:

正如你在这个问题中看到的,你应该:

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

Above code changes the text color of the menu action items for API >= v21.

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

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

Above is the code for API < v21

以上是API < v21的代码。

#7


12  

I went about it programmatically like this:

我以编程的方式进行

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

#8


6  

The short answer is YES. lucky you!
To do so, you need to override some styles of the Android default styles :

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

First, look at the definition of the themes in 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>

So, the appearance of the text in the menu is in @android:style/TextAppearance.Widget.IconMenu.Item
Now, in the definition of the styles :

因此,菜单中的文本的外观是@android:style/TextAppearance.Widget.IconMenu。项目现在,在风格的定义中:

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

So now we have the name of the color in question, if you look in the color folder of the resources of the system :

现在我们有了要讨论的颜色的名称,如果你查看系统资源的颜色文件夹:

<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>

Finally, here is what you need to do :

最后,你需要做的是:

Override "TextAppearance.Widget.IconMenu.Item" and create your own style. Then link it to your own selector to make it the way you want. Hope this helps you. Good luck!

TextAppearance.Widget.IconMenu覆盖”。创造你自己的风格。然后将它链接到您自己的选择器,使其成为您想要的方式。希望这能帮助你。好运!

#9


6  

Options menu in android can be customized to set the background or change the text appearance. The background and text color in the menu couldn’t be changed using themes and styles. The android source code (data\res\layout\icon_menu_item_layout.xml)uses a custom item of class “com.android.internal.view.menu.IconMenuItem”View for the menu layout. We can make changes in the above class to customize the menu. To achieve the same, use LayoutInflater factory class and set the background and text color for the view.

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


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


#10


6  

Thanks for the code example. I had to modify it go get it to work with a context menu. This is my solution.

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

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

For me this works with Android 1.6, 2.03 and 4.03.

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

#11


5  

I used the html tag to change a single item's text colour when the menu item is inflated. Hope it would be helpful.

我使用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;
}

#12


4  

i found it Eureka !!

我找到了,尤利卡!!

in your app theme:

在你的应用程序主题:

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

here is your action bar theme:

这是你的动作酒吧主题:

<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>

and here is your popup theme:

这是你的弹出式主题:

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

Cheers ;)

干杯,)

#13


3  

SIMPLEST way to make custom menu color for single toolbar, not for AppTheme

最简单的方法是为单个工具栏创建自定义菜单颜色,而不是为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>

usual toolbar on styles.xml

常用工具栏上styles.xml

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

our custom toolbar style

我们的自定义工具栏风格

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

#14


2  

Thanks to max.musterman, this is the solution I got to work in level 22:

多亏了马克斯。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);
}

The hardcoded Color.BLACK could become an additional parameter to the setMenuTextColor method. Also, I only used this for menu items which were android:showAsAction="never".

硬编码的颜色。黑色可以成为setMenuTextColor方法的附加参数。另外,我只在菜单项中使用了android:showAsAction="never"。

#15


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

#16


1  

Sephy's solution doesn't work. It's possible to override the options menu item text appearance using the method described above, but not the item or menu. To do that there are essentially 3 ways:

Sephy的解决方案是行不通的。可以使用上面描述的方法覆盖选项菜单项文本外观,但不能覆盖项或菜单。要做到这一点,基本上有三种方法:

  1. How to change the background color of the options menu?
  2. 如何更改选项菜单的背景色?
  3. Write your own view to display and override onCreateOptionsMenu and onPrepareOptionsMenu to get the results you want. I state this generally because you can generally do whatever you want in these methods, but you probably won't want to call into super().
  4. 编写自己的视图来显示和覆盖onCreateOptionsMenu和onPrepareOptionsMenu,以得到您想要的结果。我之所以这样描述,是因为您通常可以在这些方法中执行您想要的任何操作,但是您可能不希望调用super()。
  5. Copy code from the open-source SDK and customize for your behavior. The default menu implementation used by Activity will no longer apply.
  6. 从开源SDK中复制代码并为您的行为定制。活动使用的默认菜单实现将不再适用。

See Issue 4441: Custom Options Menu Theme for more clues.

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

#17


1  

try this code....

试试这个代码....

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

#18


1  

Simply add this to your theme

简单地把它添加到你的主题中

<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>

Tested on API 21

测试API 21

#19


1  

You can set color programmatically.

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

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

        }
    });
}

#20


1  

My situation was settings text color in the options menu (main app menu showed on menu button press).

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

Tested in API 16 with appcompat-v7-27.0.2 library, AppCompatActivity for MainActivity and AppCompat theme for the application in AndroidManifest.xml.

在API 16中使用AppCompat -v7-27.0.2库、主活动的AppCompatActivity和AndroidManifest.xml应用程序的AppCompat主题进行测试。

styles.xml:

styles.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>

Don't know if that textColorSecondary affects other elements but it controls the menu text color.

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


I searched some examples on the topic but all ready-to-use snippets didn't work.

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

So I wanted to investigate it with the source code for the appcompat-v7 library (specifically with the res folder of the .aar package).

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

Though in my case I used Eclipse with exploded .aar dependencies. So I could change the default styles and check the results. Don't know how to explode the libraries to use with Gradle or Android Studio directly. It deserves another thread of investigation.

虽然在我的例子中我使用了Eclipse和爆炸性的。aar依赖项。所以我可以改变默认样式并检查结果。不知道如何将库与Gradle或Android Studio直接使用。它值得进一步研究。

So my purpose was so find which color in the res/values/values.xml file is used for the menu text (I was almost sure the color was there).

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

  1. I opened that file, then duplicated all colors, put them below the default ones to override them and assigned #f00 value to all of them.
  2. 我打开了那个文件,然后复制了所有的颜色,把它们放在默认的颜色下面以覆盖它们,并将#f00值分配给所有的颜色。
  3. Start the app.
  4. 启动应用程序。
  5. Many elements had red background or text color. And the menu items too. That was what I needed.
  6. 许多元素都有红色的背景或文本颜色。还有菜单项目。这正是我所需要的。
  7. Removing my added colors by blocks of 5-10 lines I ended with the secondary_text_default_material_light color item.
  8. 用5-10行代码块删除添加的颜色,最后使用secondary_text_default_material_light颜色项。
  9. Searching that name in the files within the res folder (or better within res/colors) I found only one occurrence in the color/abc_secondary_text_material_light.xml file (I used Sublime Text for these operations so it's easier to find thing I need).
  10. 在res文件夹(或者在res/colors中)的文件中搜索该名称,我发现颜色/abc_secondary_text_material_light中只有一个名称出现。xml文件(我对这些操作使用了崇高的文本,以便更容易找到我需要的东西)。
  11. Back to the values.xml 8 usages were found for the @color/abc_secondary_text_material_light.
  12. 回值。可以找到@color/abc_secondary_text_material_light的xml 8用法。
  13. It was a Light theme so 4 left in 2 themes: Base.ThemeOverlay.AppCompat.Light and Platform.AppCompat.Light.
  14. 这是一个轻主题,所以4有两个主题:Base.ThemeOverlay.AppCompat。光和Platform.AppCompat.Light。
  15. The first theme was a child of the second one so there were only 2 attributes with that color resource: android:textColorSecondary and android:textColorTertiaryin the Base.ThemeOverlay.AppCompat.Light.
  16. 第一个主题是第二个主题的孩子,所以这个颜色资源只有两个属性:android:textColorSecondary和android: textcolortriaryin The Base.ThemeOverlay.AppCompat.Light。
  17. Changing their values directly in the values.xml and running the app I found that the final correct attribute was android:textColorSecondary.
  18. 在值中直接改变它们的值。我发现最终正确的属性是android:textColorSecondary。
  19. Next I needed a theme or another attribute so I could change it in my app's style.xml (because my theme had as the parent the Theme.AppCompat.Light and not the ThemeOverlay.AppCompat.Light).
  20. 接下来我需要一个主题或另一个属性,这样我就可以在我的应用中改变它的样式。xml(因为我的主题是父类。appcompat。轻,而不是覆盖层。appcompat .轻)。
  21. I searched in the same file for the Base.ThemeOverlay.AppCompat.Light. It had a child ThemeOverlay.AppCompat.Light.
  22. 我在同一个文件中搜索Base.ThemeOverlay.AppCompat.Light。上面有个孩子,appcompat, light。
  23. Searching for the ThemeOverlay.AppCompat.Light I found its usage in the Base.Theme.AppCompat.Light.DarkActionBar theme as the actionBarPopupTheme attribute value.
  24. 寻找ThemeOverlay.AppCompat。我在地下室找到了它的用法。将DarkActionBar主题作为actionBarPopupTheme属性值。
  25. My app's theme Theme.AppCompat.Light.DarkActionBar was a child of the found Base.Theme.AppCompat.Light.DarkActionBar so I could use that attribute in my styles.xml without problems.
  26. 我的应用程序主题Theme.AppCompat.Light。DarkActionBar是一个被发现的Base.Theme.AppCompat.Light的孩子。我可以在样式中使用这个属性。xml没有问题。
  27. As it's seen in the example code above I created a child theme from the mentioned ThemeOverlay.AppCompat.Light and changed the android:textColorSecondary attribute.
  28. 正如上面的示例代码所示,我从上面提到的ThemeOverlay.AppCompat创建了一个子主题。修改了android:textColorSecondary属性。

如何在Android中改变菜单项的文本颜色?

#21


0  

This is how you can color a specific menu item with color, works for all API levels:

这就是如何用颜色为特定的菜单项着色的方法,适用于所有的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));
                                }
                            }
                        }
                    }
                });
            }
        }
    }
}

By doing that you loose the background selector effect, so here is the code to apply a custom background selector to all of the menu item children.

通过这样做,您将失去背景选择器效果,因此下面的代码将应用自定义背景选择器到所有的菜单项子元素。

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

Here is the helper function also:

下面是助手函数:

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

#22


0  

For changing the text color, you can just set a custom view for the MenuItem, and then you can define the color for the text.

要更改文本颜色,只需为MenuItem设置一个自定义视图,然后可以为文本定义颜色。

Sample Code : MenuItem.setActionView()

示例代码:MenuItem.setActionView()

#23


0  

in Kotlin I wrote these extensions:

在Kotlin,我写了这些扩展:

fun MenuItem.setTitleColor(color: Int) {                                                        
    val hexColor = Integer.toHexString(color).toUpperCase().substring(2)                        
    val html = "<font color='#" + hexColor + "'>" + this.title.toString() + "</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)                                                                     
    }                                                                                           
}  

and used like this:

和使用:

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