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

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


当前回答

为了改变文本颜色,你可以为MenuItem设置一个自定义视图,然后你可以为文本定义颜色。 示例代码:MenuItem.setActionView()

其他回答

如果你使用的菜单是<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"/>

希望对你有所帮助。

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

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

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>

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


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

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

不过在我的例子中,我使用了带有爆炸性.aar依赖项的Eclipse。因此,我可以更改默认样式并检查结果。不知道如何爆炸库与Gradle或Android Studio直接使用。它值得进行另一项调查。

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

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. Start the app. Many elements had red background or text color. And the menu items too. That was what I needed. Removing my added colors by blocks of 5-10 lines I ended with the secondary_text_default_material_light color item. 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). Back to the values.xml 8 usages were found for the @color/abc_secondary_text_material_light. It was a Light theme so 4 left in 2 themes: Base.ThemeOverlay.AppCompat.Light and Platform.AppCompat.Light. 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. Changing their values directly in the values.xml and running the app I found that the final correct attribute was android:textColorSecondary. 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). I searched in the same file for the Base.ThemeOverlay.AppCompat.Light. It had a child ThemeOverlay.AppCompat.Light. Searching for the ThemeOverlay.AppCompat.Light I found its usage in the Base.Theme.AppCompat.Light.DarkActionBar theme as the actionBarPopupTheme attribute value. 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. 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.

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

这是你如何用颜色给一个特定的菜单项上色,适用于所有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);
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
    }
}

下面是helper函数:

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

只要去 值-样式和内部样式和类型 你的颜色