How to change the text color of individual action elements in an ActionBAR PROGRAM?

In mine ActionBar, I have MenuItemone that has an attribute showAsAction="always", as shown in the image below. Based on the connection the user has on our servers, I will change the text as well as the color of the element.

Current action bar

Currently, I can easily change the text of an element in 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);
}

This works great and, if possible, I would also like to change the color of the text here. I saw a lot of posts about how to change the text of all overflow elements or the header to ActionBar, but nothing about changing a single element of the PROGRAM action. The current color is set to xml, I want to change it dynamically.

+2
1

, 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;
}

results

+6

All Articles