我可以改变一个菜单项的背景颜色在安卓?
如果有人对此有任何解决方案,请让我知道。最后一个选项显然是自定义,但是否有任何方法可以在不自定义的情况下更改文本颜色。
我可以改变一个菜单项的背景颜色在安卓?
如果有人对此有任何解决方案,请让我知道。最后一个选项显然是自定义,但是否有任何方法可以在不自定义的情况下更改文本颜色。
当前回答
Sephy的方法不管用。可以使用上述方法覆盖选项菜单项文本外观,但不能覆盖项或菜单。要做到这一点,基本上有3种方法:
如何更改选项菜单的背景颜色? 写你自己的视图来显示和覆盖onCreateOptionsMenu和onPrepareOptionsMenu来获得你想要的结果。我之所以笼统地说明这一点,是因为您通常可以在这些方法中做任何您想做的事情,但您可能不想调用super()。 从开源SDK复制代码,并自定义您的行为。Activity使用的默认菜单实现将不再适用。
参见第4441期:自定义选项菜单主题了解更多线索。
其他回答
添加textColor如下所示
<style name="MyTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light">
<item name="android:textColor">@color/radio_color_gray</item>
</style>
并在xml文件中的工具栏中使用它
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/MyTheme.PopupOverlay" />
主题中的一句话:)
<item name="android:actionMenuTextColor">@color/your_color</item>
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);
}
在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)
Sephy的方法不管用。可以使用上述方法覆盖选项菜单项文本外观,但不能覆盖项或菜单。要做到这一点,基本上有3种方法:
如何更改选项菜单的背景颜色? 写你自己的视图来显示和覆盖onCreateOptionsMenu和onPrepareOptionsMenu来获得你想要的结果。我之所以笼统地说明这一点,是因为您通常可以在这些方法中做任何您想做的事情,但您可能不想调用super()。 从开源SDK复制代码,并自定义您的行为。Activity使用的默认菜单实现将不再适用。
参见第4441期:自定义选项菜单主题了解更多线索。