2017-05-25 50 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

嘗試以上解決方案,但無法正常工作。 –

相關問題