bjo*_*son 2 java android android-actionbar
在我的中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);
}
Run Code Online (Sandbox Code Playgroud)
这很有效,如果可能的话,我也希望在这里更改文本的颜色.我看过很多关于如何将所有溢出项目或标题更改为ActionBar
自身的文章,但没有关于改变单个行动项目的任何内容.当前颜色设置为xml,我想动态更改它.
好吧,每个MenuItem
View
实际上都是它的子类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;
}
Run Code Online (Sandbox Code Playgroud)
结果
归档时间: |
|
查看次数: |
4137 次 |
最近记录: |