[英]How to change individual action item text color in ActionBar PROGRAMMATICALLY?
在我的ActionBar
,我有一個MenuItem
,其屬性showAsAction="always"
,如下圖所示。 根據用戶與服務器的連接,我將更改項目的文本和顏色。
目前,我可以在onPrepareOptionsMenu(...)
輕松更改項目的文本:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.action_connection);
if(mIsConnected) {
item.setTitle(R.string.action_connected);
} else {
item.setTitle(R.string.action_not_connected);
}
return super.onPrepareOptionsMenu(menu);
}
這很有效,如果可能的話,我也希望在這里更改文本的顏色。 我已經看過很多關於如何將所有溢出項目或標題的文本更改為ActionBar
本身的帖子,但沒有關於如何更改單個操作項目PROGRAMMATICY。 當前顏色設置為xml,我想動態更改它。
好吧,每個MenuItem
View
實際上是TextView
的子TextView
,因此這將使更改文本顏色更容易。
可用於定位MenuItem
View
簡單方法是View.findViewsWithText
。
一個基本的實現,考慮到你只有一個你有興趣改變的MenuItem
,可能看起來像這樣:
private final ArrayList<View> mMenuItems = Lists.newArrayList();
private boolean mIsConnected;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Add a your MenuItem
menu.add("Connected").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
// Adjust the text color based on the connection
final TextView connected = !mMenuItems.isEmpty() ? (TextView) mMenuItems.get(0) : null;
if (connected != null) {
connected.setTextColor(mIsConnected ? Color.GREEN : Color.RED);
} else {
// Find the "Connected" MenuItem View
final View decor = getWindow().getDecorView();
decor.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mIsConnected = true;
// Remove the previously installed OnGlobalLayoutListener
decor.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Traverse the decor hierarchy to locate the MenuItem
decor.findViewsWithText(mMenuItems, "Connected",
View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
// Invalidate the options menu to display the new text color
invalidateOptionsMenu();
}
});
}
return true;
}
結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.