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

sun*_*nil 154 android textcolor menuitem layout-inflater

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

如果有人对此有任何解决方案,请告诉我.最后一个选项显然是要自定义它,但是有没有办法在不自定义的情况下更改文本颜色.

Muh*_*ifi 326

主题中的一个简单的行:)

<item name="android:actionMenuTextColor">@color/your_color</item>
Run Code Online (Sandbox Code Playgroud)

  • 要支持较低的API版本,请使用`<item name ="actionMenuTextColor"> @ color/your_color </ item>`不要使用Android名称空间 (46认同)
  • 注意:这必须在你的应用程序的主要主题定义中,而不是在`actionBarStyle`中.它在`actionBarStyle`中不起作用,即使这似乎合乎逻辑! (17认同)
  • 不适用于API 16(目标是22). (7认同)
  • 为什么这不是更多的赞成?! (6认同)
  • 似乎不适用于`Theme.MaterialComponents.DayNight` (6认同)
  • @ColinM.它必须进入_a_主题.如果在工具栏上设置`theme`属性,则可以正常工作. (5认同)
  • 不适用于API 21.(目标是21) (2认同)
  • 无论是否使用android:namespace都不适合我.它被添加到主应用主题中. (2认同)
  • 我仍然完全无法改变文字颜色.我的整体主题textcolor只是偏爱.有帮助吗?这些答案都不起作用. (2认同)

Mar*_*hon 104

似乎是一个

  <item name="android:itemTextAppearance">@style/myCustomMenuTextAppearance</item>
Run Code Online (Sandbox Code Playgroud)

在我的主题和

   <style name="myCustomMenuTextAppearance" parent="@android:style/TextAppearance.Widget.IconMenu.Item">
        <item name="android:textColor">@android:color/primary_text_dark</item>
    </style>
Run Code Online (Sandbox Code Playgroud)

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

  • 这适用于上下文菜单项(不是菜单按钮中的菜单项),这是我一直在寻找的.比整个LayoutFactory混乱简单得多. (4认同)

max*_*ann 79

您可以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);
}
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用(在KitKat设备上). (15认同)
  • 这对4.4和5+都适用于我```menu.findItem(R.id.menu_item_id);```而不是```menu.getItem()``` (9认同)
  • 解决方案只适用于溢出的项目....我不想改变通过设置showAsAction可见的项目颜色:"总是" (5认同)

Sud*_*ara 50

如果您使用具有主题的新工具栏,则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>`
Run Code Online (Sandbox Code Playgroud)

根据我得到的结果,
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"/>
Run Code Online (Sandbox Code Playgroud)


小智 28

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

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 您的回答帮助我将 MenuItem 文本设置为粗体。(s.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, s.length(), 0); 谢谢! (3认同)

Mih*_*edi 28

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

app:itemTextColor="your color"
Run Code Online (Sandbox Code Playgroud)

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

app:itemIconTint="your color"
Run Code Online (Sandbox Code Playgroud)

例:

<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"/>
Run Code Online (Sandbox Code Playgroud)

希望它会对你有所帮助.


pou*_*uya 15

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

<item name="android:textColorPrimary">yourColor</item>
Run Code Online (Sandbox Code Playgroud)

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

<item name="actionMenuTextColor">@android:color/holo_green_light</item>
Run Code Online (Sandbox Code Playgroud)

以上是API <v21的代码


小智 13

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

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:itemTextAppearance">@style/menuItem</item>
</style>
Run Code Online (Sandbox Code Playgroud)

然后创建一个样式,将菜单项的 textColor 设置为您想要的颜色。

<style name="menuItem" parent="Widget.AppCompat.TextView.SpinnerItem">
    <item name="android:textColor">@color/black</item>
</style>
Run Code Online (Sandbox Code Playgroud)

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


ali*_*dro 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;
}
Run Code Online (Sandbox Code Playgroud)


Sep*_*phy 7

简短的回答是肯定的.幸运的你!
为此,您需要覆盖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>
Run Code Online (Sandbox Code Playgroud)

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

<style name="TextAppearance.Widget.IconMenu.Item" parent="TextAppearance.Small">
<item name="android:textColor">?textColorPrimaryInverse</item>
</style>
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

最后,这是您需要做的:

覆盖"TextAppearance.Widget.IconMenu.Item"并创建自己的样式.然后将其链接到您自己的选择器,使其按您想要的方式进行.希望这对你有所帮助.祝好运!


And*_*ewS 7

SIMPLEST为单个工具栏制作自定义菜单颜色的方法,而不是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>
Run Code Online (Sandbox Code Playgroud)

styles.xml上的常用工具栏

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
Run Code Online (Sandbox Code Playgroud)

自定义工具栏样式

<style name="AppTheme.AppBarOverlay.MenuBlue">
    <item name="actionMenuTextColor">@color/blue</item>
</style>
Run Code Online (Sandbox Code Playgroud)


Mic*_*ogl 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);
}
Run Code Online (Sandbox Code Playgroud)

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


小智 6

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

<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>
Run Code Online (Sandbox Code Playgroud)

在 API 21 上测试

  • 最好使用`&lt;style name="AppTheme.ItemTextStyle"parent="@android:style/TextAppearance.Widget"&gt;`,否则溢出菜单中的文本显得太小。另请注意,此技术仅适用于 Android 5 及更高版本。 (2认同)

Ami*_*ndi 6

在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)                                                                     
    }                                                                                           
}  
Run Code Online (Sandbox Code Playgroud)

并像这样使用:

menu.findItem(R.id.main_settings).setTitleColor(Color.RED)
Run Code Online (Sandbox Code Playgroud)


小智 6

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

<style name="AppToolbar" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:itemTextAppearance">@style/menu_item_color</item>
</style>
Run Code Online (Sandbox Code Playgroud)

在哪里

<style name="menu_item_color">
<item name="android:textColor">@color/app_font_color</item>
</style>
Run Code Online (Sandbox Code Playgroud)


Abh*_*mar 5

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


  • `03-23 19:45:25.134:E/AndroidRuntime(26761):java.lang.IllegalStateException:已经在此LayoutInflater上设置了工厂 (3认同)

Far*_*uti 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>
Run Code Online (Sandbox Code Playgroud)

这是你的动作栏主题:

<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>
Run Code Online (Sandbox Code Playgroud)

这是你的弹出主题:

 <style name="ActionBarPopupTheme">
    <item name="android:textColor">@color/menu_text_color</item>
    <item name="android:background">@color/menu_bg_color</item>
 </style>
Run Code Online (Sandbox Code Playgroud)

干杯;)


lig*_*per 5

感谢 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);
}
Run Code Online (Sandbox Code Playgroud)

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


Asi*_*sim 5

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

<item name="android:textColorPrimary">?android:attr/textColorPrimaryInverse</item>
Run Code Online (Sandbox Code Playgroud)


Ale*_*huk 5

如果您想为单个菜单项设置颜色,自定义工具栏主题并不是正确的解决方案。为此,您可以使用 android:actionLayout 和菜单项的操作视图。

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

菜单按钮.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>
Run Code Online (Sandbox Code Playgroud)

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

然后在菜单的 XML 布局文件中包含app:actionLayout="@layout/menu_button"如下内容:

主菜单.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>
Run Code Online (Sandbox Code Playgroud)

最后重写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;
}
Run Code Online (Sandbox Code Playgroud)

...或片段:

@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
    });
}
Run Code Online (Sandbox Code Playgroud)

有关操作视图的更多详细信息,请参阅Android 开发人员指南