2017-05-25 49 views
1

我试图动态更改菜单项文本颜色。Android更改菜单项动态文本颜色

我有一个菜单图标有效的解决方案,它采用了彩色滤光片如下:

Drawable drawable = menuItem.getIcon(); 

     if (drawable != null) { 
      drawable.mutate(); 
      drawable.setColorFilter(new 
        PorterDuffColorFilter(Color.parseColor(color), PorterDuff.Mode.MULTIPLY)); 
     } 
     menuItem.setIcon(drawable); 

输出:enter image description here

我无法改变,菜单项文本的颜色。为了使这项工作我用下面的代码:

SpannableString s = new SpannableString(menuItem.getTitle()); 
       s.setSpan(new ForegroundColorSpan(Color.parseColor(color)), 0, s.length(), 0); 
       menuItem.setTitle(s); 

输出:enter image description here

“SAVE”的颜色是什么,我试图改变。

任何人都可以帮我解决这个问题吗?

回答

0

添加菜单风格

<style name="optionMenuTextApearance" parent="@style/Theme.Sherlock.Light"> 
    <item name="actionMenuTextColor">@color/white</item> 
    <item name="android:actionMenuTextColor">@color/white</item> 
</style> 

称它在菜单

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

运行时更改菜单颜色

@Override 
public boolean onPrepareOptionsMenu(Menu menu) { 
    boolean result = super.onPrepareOptionsMenu(menu); 
    styleMenuButton(); 
    return result; 
} 

private void styleMenuButton() { 
    // Find the menu item you want to style 
    View view = findViewById(R.id.YOUR_MENU_ITEM_ID_HERE); 

    // Cast to a TextView instance if the menu item was found 
    if (view != null && view instanceof TextView) { 
     ((TextView) view).setTextColor(Color.BLUE); // Make text colour blue 
    } 
} 
+0

有没有办法从java代码中指定文本颜色,而不是在XML中指定它? 例如,我在style/XML中指定actionMenuTextColor = white,并且希望在运行时将其更改为RED。怎么做? –

+0

检查上面的代码 –

+0

欲如下所示改变的活动,“保存”菜单项的颜色: '@覆盖 公共布尔onCreateOptionsMenu(菜单菜单){ MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu_done,menu); MenuItem saveMenuItem = menu.findItem(R.id.action_done); //我要更改saveMenuItem文本 return super.onCreateOptionsMenu(menu); }' –

1

试试这个,

在样式添加这个主题。

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">  
    <item name="actionMenuTextColor">@color/text_color</item>  
</style> 

,并应用该主题的工具栏

android:theme="@style/AppTheme" 
+0

有没有一种方法可以从java代码中指定文本颜色,而不是在XML中指定它? 例如,我在style/XML中指定actionMenuTextColor = white,并且希望在运行时将其更改为RED。怎么做? –

+0

检查此https://stackoverflow.com/questions/8614293/android-get-view-reference-to-a-menu-item希望它会帮助你。 –

0

你应该设置你的SpannableString你的菜单项。 添加以下行您建立一个SpannableString后:

menuItem.setTitle(s); 

由于您的menuItem.getTitle()仅提供用于制造SpannableString,而不是引用作为菜单项标题的字符串值。

+0

我必须改变菜单项文字颜色不是操作栏的标题颜色。 –

+0

@PrashantKawtikwar对不起,我很困惑,试试编辑答案。 – viz

+0

尝试以上解决方案,但无法正常工作。 –

相关问题