我可以改变一个菜单项的背景颜色在安卓?
如果有人对此有任何解决方案,请让我知道。最后一个选项显然是自定义,但是否有任何方法可以在不自定义的情况下更改文本颜色。
我可以改变一个菜单项的背景颜色在安卓?
如果有人对此有任何解决方案,请让我知道。最后一个选项显然是自定义,但是否有任何方法可以在不自定义的情况下更改文本颜色。
当前回答
为了改变文本颜色,你可以为MenuItem设置一个自定义视图,然后你可以为文本定义颜色。 示例代码:MenuItem.setActionView()
其他回答
通过使用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);
}
将它添加到我的styles.xml中对我有用
<item name="android:textColorPrimary">?android:attr/textColorPrimaryInverse</item>
在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)
只需将此添加到您的主题
<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测试
我使用的是材质设计,当工具栏在一个小屏幕上时,点击更多选项会显示一个空白的白色下拉框。为了解决这个问题,我想在主AppTheme中添加了这个:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="android:itemTextAppearance">@style/menuItem</item>
</style>
然后创建了一个样式,你可以将菜单项的textColor设置为你想要的颜色。
<style name="menuItem" parent="Widget.AppCompat.TextView.SpinnerItem">
<item name="android:textColor">@color/black</item>
</style>
父名称widget。appcompat . textview . spinneritem我不认为这太重要,它应该仍然工作。