Skip to content Skip to sidebar Skip to footer

How To Change Individual Action Item Text Color In Actionbar Programmatically?

In my ActionBar, I have a MenuItem that has attribute showAsAction='always' as seen in the image below. Based on the connection a user has to our servers, I will be changing the te

Solution 1:

Well, each MenuItemView is actually a subclass of TextView, so this will make changing the text color easier.

A simple method you can use to locate a MenuItemView is View.findViewsWithText.

A basic implementation, considering you just have that one MenuItem you're interested in changing, might look something like this:

privatefinal ArrayList<View> mMenuItems = Lists.newArrayList();
privateboolean mIsConnected;

@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
    // Add a your MenuItem
    menu.add("Connected").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    // Adjust the text color based on the connectionfinalTextViewconnected= !mMenuItems.isEmpty() ? (TextView) mMenuItems.get(0) : null;
    if (connected != null) {
        connected.setTextColor(mIsConnected ? Color.GREEN : Color.RED);
    } else {
        // Find the "Connected" MenuItem ViewfinalViewdecor= getWindow().getDecorView();
        decor.getViewTreeObserver().addOnGlobalLayoutListener(newOnGlobalLayoutListener() {

            @OverridepublicvoidonGlobalLayout() {
                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();
            }

        });

    }
    returntrue;
}

Results

results

Post a Comment for "How To Change Individual Action Item Text Color In Actionbar Programmatically?"