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

发布于 2024-09-15 05:07:37 字数 99 浏览 13 评论 0原文

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

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

Can I change the background color of a Menu item in 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

帅气称霸 2024-09-22 05:07:50

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

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

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);
}
南城追梦 2024-09-22 05:07:50

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

示例代码:MenuItem.setActionView()

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.

Sample Code : MenuItem.setActionView()

初相遇 2024-09-22 05:07:50

只需前往
值 - 样式和内部样式和类型
你的颜色

Simply just go to
Values - styles and inside styles and type
your color

初心 2024-09-22 05:07:49

添加如下 textColor

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

并在 xml 文件的 Toolbar 中使用它

<androidx.appcompat.widget.Toolbar
     android:id="@+id/toolbar"
     android:layout_width="match_parent"
     android:layout_height="?attr/actionBarSize"
     app:popupTheme="@style/MyTheme.PopupOverlay" /> 

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" /> 
迷离° 2024-09-22 05:07:49

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

API 16 中使用 appcompat-v7-27.0.2 库、针对 MainActivityAppCompat 的 AppCompatActivity 进行测试AndroidManifest.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>

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


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

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

尽管在我的例子中,我使用了具有分解的 .aar 依赖项的 Eclipse。所以我可以更改默认样式并检查结果。不知道如何分解库以直接与 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,发现 @color/abc_secondary_text_material_light 有 8 种用法。
  7. 这是一个 Light 主题,因此 4 个主题只剩下 2 个主题:Base.ThemeOverlay.AppCompat.LightPlatform.AppCompat.Light
  8. 第一个主题是第二个主题的子主题,因此该颜色资源只有 2 个属性:Base.ThemeOverlay 中的 android:textColorSecondaryandroid:textColorTertiary .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 是找到的 Base.Theme.AppCompat.Light.DarkActionBar 的子主题,因此我可以在我的 中使用该属性styles.xml 没有问题。
  14. 正如上面的示例代码所示,我从提到的 ThemeOverlay.AppCompat.Light 创建了一个子主题,并更改了 android:textColorSecondary 属性。

https: //i.sstatic.net/plzdq.png

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.

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.


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

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.

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

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

https://i.sstatic.net/plzdq.png

王权女流氓 2024-09-22 05:07:49

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

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

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

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:

  1. How to change the background color of the options menu?
  2. 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().
  3. Copy code from the open-source SDK and customize for your behavior. The default menu implementation used by Activity will no longer apply.

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

毅然前行 2024-09-22 05:07:49

试试这个代码....

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

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);
    }
我很OK 2024-09-22 05:07:48

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

If you want to set color for an individual menu item, customizing a toolbar theme is not the right solution. To achieve this, you can make use of android:actionLayout and an action view for the menu item.

First create an XML layout file for the action view. In this example we use a button as an action view:

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>

In the code snippet above, we use android:textColor="?android:attr/colorAccent" to customize button text color.

Then in your XML layout file for the menu, include app:actionLayout="@layout/menu_button" as shown below:

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>

Last override the onCreateOptionsMenu() method in your activity:

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

...or fragment:

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

For more details on action views, see the Android developer guide.

等往事风中吹 2024-09-22 05:07:48

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

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

        }
    });
}

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

        }
    });
}
波浪屿的海角声 2024-09-22 05:07:48
@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
@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
时光清浅 2024-09-22 05:07:47

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

<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 上进行测试

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

习ぎ惯性依靠 2024-09-22 05:07:47

感谢 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" 的菜单项。

Thanks to max.musterman, this is the solution I got to work in level 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".

中二柚 2024-09-22 05:07:47

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

<item name="android:textColorPrimary">?android:attr/textColorPrimaryInverse</item>

Adding this into my styles.xml worked for me

<item name="android:textColorPrimary">?android:attr/textColorPrimaryInverse</item>
墟烟 2024-09-22 05:07:46

感谢您提供代码示例。
我必须修改它,使其能够与上下文菜单一起使用。
这是我的解决方案。

    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。

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.

我纯我任性 2024-09-22 05:07:46

我找到了尤里卡!!

在您的应用程序主题中:

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

干杯;)

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

删除→记忆 2024-09-22 05:07:45

简短的回答是肯定的。你真幸运!
为此,您需要覆盖 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”并创建您自己的样式。然后将其链接到您自己的选择器以使其成为您想要的方式。
希望这对您有帮助。
祝你好运!

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

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 :

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

夏见 2024-09-22 05:07:45

Android 中的选项菜单可以自定义设置背景或更改文本外观。无法使用主题和样式更改菜单中的背景和文本颜色。 android源代码(data\res\layout\icon_menu_item_layout.xml)使用类“com.android.internal.view.menu.IconMenuItem”View的自定义项进行菜单布局。我们可以在上面的类中进行更改来自定义菜单。要实现相同的目的,请使用 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);
}


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.


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


暮年 2024-09-22 05:07:44

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

SIMPLEST way to make custom menu color for single toolbar, not for 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

<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>
玩心态 2024-09-22 05:07:44

要更改菜单项文本颜色,请使用下面的

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

to change menu item text color use below code

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

where

<style name="menu_item_color">
<item name="android:textColor">@color/app_font_color</item>
</style>
箜明 2024-09-22 05:07:43

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

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

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

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

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

I was using Material design and when the toolbar was on a small screen clicking the more options would show a blank white drop down box. To fix this I think added this to the main AppTheme:

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

And then created a style where you set the textColor for the menu items to your desired colour.

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

The parent name Widget.AppCompat.TextView.SpinnerItem I don't think that matters too much, it should still work.

情深如许 2024-09-22 05:07:43

当菜单项膨胀时,我使用 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;
}

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

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;
}
煮茶煮酒煮时光 2024-09-22 05:07:42

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

in Kotlin I wrote these extensions:

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

and used like this:

menu.findItem(R.id.main_settings).setTitleColor(Color.RED)
乞讨 2024-09-22 05:07:42

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

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

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

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

上面是 API < 的代码v21

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.

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

Above is the code for API < v21

自演自醉 2024-09-22 05:07: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;
}

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;
}
花辞树 2024-09-22 05:07:41

如果您将菜单用作 那么只需在 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"/>

希望它会对您有所帮助。

If you are using menu as <android.support.design.widget.NavigationView /> then just add below line in 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.

沫雨熙 2024-09-22 05:07:40

如果您使用新的工具栏,且主题为 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"/>

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

 <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.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"/>
变身佩奇 2024-09-22 05:07:39

你的主题中只有一行简单的内容:)

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

One simple line in your theme :)

<item name="android:actionMenuTextColor">@color/your_color</item>
魂归处 2024-09-22 05:07:39

似乎

  <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 中的 an 更改了列表项的样式,但没有更改菜单项的样式。

It seems that an

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

in my theme and

   <style name="myCustomMenuTextAppearance" 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.

始终不够 2024-09-22 05:07:39

您可以使用 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);
}

You can change the color of the MenuItem text easily by using SpannableString instead of 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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文