menuitem - How to change the Text color of Menu item in Android?

menuitem - How to change the Text color of Menu item in Android?

Ganesh Quique Author: Ganesh Quique Date: 2022-08-15
menuitem - How to change the Text color of Menu item in Android?

All you need to know about menuitem - How to change the Text color of Menu item in Android? , in addintion to popupmenu - How to change the text color and size of a pop up menu in android? , How can I change the color of the textView android.R.layout.simple_spinner_dropdown_item? , android - How do you change the textcolor of the list items in an AlertDialog , android - Change MenuItem text color programmatically

    Question:

    Can I change the background color of a Menu item in Android?

    Please let me know if anyone have any solution to this. The last option will be obviously to customize it but is there any way for changing the text color without customizing it.


    Solution 1:

    One simple line in your theme :)

    <item name="android:actionMenuTextColor">@color/your_color</item>
    

    Solution 2:

    It seems that an

      <item name="android:itemTextAppearance">@style/myCustomMenuTextAppearance</item>
    

    in my theme and

       <style name="myCustomMenuTextAppearance" parent="@android:style/TextAppearance.Widget.IconMenu.Item">
            <item name="android:textColor">@android:color/primary_text_dark</item>
        </style>
    

    in styles.xml change the style of list-items but not menu items.

    Solution 3:

    You can change the color of the MenuItem text easily by using SpannableString instead of String.

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.your_menu, menu);
    
        int positionOfMenuItem = 0; // or whatever...
        MenuItem item = menu.getItem(positionOfMenuItem);
        SpannableString s = new SpannableString("My red MenuItem");
        s.setSpan(new ForegroundColorSpan(Color.RED), 0, s.length(), 0);
        item.setTitle(s);
    }
    

  1. popupmenu - How to change the text color and size of a pop up menu in android?
  2. Question:

    Text color in pop up menu is not changing even changed in styles. Background color is changing with respect to the color in styles.xml but the text color and text size are not reflecting.

    //Creating the instance of PopupMenu  
    PopupMenu popup = new PopupMenu(mContext, holder.im_overflow);      
    //Inflating the Popup using xml file  
    popup.getMenuInflater().inflate(R.menu.list_overflow_menu, popup.getMenu());     
    //registering popup with OnMenuItemClickListener  
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {      
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            if( item.getTitle().equals("Edit")){
                callEdit();
            } else if( item.getTitle().equals("Export")) {
                callShare();
            } else if( item.getTitle().equals("Delete")) {
                callDelete();
            }
            return true;
        }
    });
    
    popup.show();
    

    Styles.xml

    <style name="AppBaseTheme" parent="@android:style/Theme.Light.NoTitleBar">
    </style>
    
    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <item name="android:popupMenuStyle">@style/PopupMenu</item>      
    </style>
    
    <style name="PopupMenu" parent="@android:style/Widget.PopupMenu">
        <item name="android:popupBackground">@android:color/white</item>
        <item name="android:textColor">#FF01F0</item>
        <item name="android:textSize">12sp</item>
    </style>
    

    But it is not changing the text color.


    Solution 1:

    You can change the text size and color by adding this code to styles.xml and use it in manifest file. For me it worked.

    <style name="AppTheme" parent="AppBaseTheme">
        <item name="android:popupMenuStyle">@style/PopupMenu</item>
        <item name="android:textAppearanceLargePopupMenu">@style/myPopupMenuTextAppearanceLarge</item>
        <item name="android:textAppearanceSmallPopupMenu">@style/myPopupMenuTextAppearanceSmall</item>
    </style>
    
    <style name="PopupMenu" parent="@android:style/Widget.PopupMenu">
        <item name="android:popupBackground">@android:color/white</item>
        <item name="android:textColor">#FF01F0</item>
        <item name="android:textSize">12sp</item>
    </style>
    
    <style name="myPopupMenuTextAppearanceSmall" parent="@android:style/TextAppearance.DeviceDefault.Widget.PopupMenu.Small">
        <item name="android:textColor">#545656</item>
        <item name="android:textSize">15sp</item>
    </style>
    
    <style name="myPopupMenuTextAppearanceLarge" parent="@android:style/TextAppearance.DeviceDefault.Widget.PopupMenu.Large">
        <item name="android:textColor">#545656</item>
        <item name="android:textSize">25sp</item>    
    </style>
    

    Solution 2:

    In my style file:

           <style name="menuStyle">
               <item name="android:layoutDirection">rtl</item>
               <item name="android:textColor">@color/onyx</item>
               <item name="android:textSize">15sp</item>
               <item name="android:fontFamily">@font/ge_ss_two_light</item>
           </style>
    

    In my java file:

            Context myContext = new ContextThemeWrapper(context, R.style.menuStyle);
            MenuBuilder menuBuilder = new MenuBuilder(context);
            MenuInflater inflater = new MenuInflater(context);
            inflater.inflate(R.menu.options_menu, menuBuilder);
    

  3. How can I change the color of the textView android.R.layout.simple_spinner_dropdown_item?
  4. Question:

    I'm creating a SpinnerAdapter using the built in resource ID android.R.layout.simple_spinner_dropdown_item

    SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_list, android.R.layout.simple_spinner_dropdown_item);
    

    but the textView which that resource ID creates has textColor Black and I need a different color. What's the best way of changing the color but keeping everything else the same?

    When I try and create my own textView layout resource in an xml file, e.g.

    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/White"
        />
    

    then it doesn't behave in the same way as android.R.layout.simple_spinner_dropdown_item because e.g. the padding is different. So

    1. Is there a way of creating my own layout resource in an xml file which inherits everything from android.R.layout.simple_spinner_dropdown_item and allows me to override the textColor?
    2. Or is the complete definition of android.R.layout.simple_spinner_dropdown_item available somewhere?
    3. Or perhaps there's an even easier way somehow?

    This question relates to another question that I've asked today (Can't change the text color with Android Action Bar drop-down navigation). I've realised that one answer to that question (and hence this question) is to create my own ArrayAdapter class which inherits from ArrayAdapter<T> so that I can always set the color in code whenever the ArrayAdapter gets used (see my answer to that question). But that seems like a very cumbersome solution :-|.

    Changing a text color shouldn't be a hard task!


    Solution 1:

    Is there a way of creating my own layout resource in an xml file which inherits everything from android.R.layout.simple_spinner_dropdown_item and allows me to override the textColor?

    No, but you can cut & paste your favorite version of simple_spinner_dropdown_item.xml to a new file then simply change the text color.

    Or is the complete definition of android.R.layout.simple_spinner_dropdown_item available somewhere?

    Yes, but there are many different versions. Which API do you like? Also you might have a copy on your hard drive already, check <android-sdk>/platforms/android-xx/data/res/layout/ (where xx is a particular API.)


    As an alternate approach you can create a custom Adapter and change the text color after you inflate each row, but the method above will be slightly faster since it doesn't involve any run time changes.

    Solution 2:

    In my style file:

           <style name="menuStyle">
               <item name="android:layoutDirection">rtl</item>
               <item name="android:textColor">@color/onyx</item>
               <item name="android:textSize">15sp</item>
               <item name="android:fontFamily">@font/ge_ss_two_light</item>
           </style>
    

    In my java file:

            Context myContext = new ContextThemeWrapper(context, R.style.menuStyle);
            MenuBuilder menuBuilder = new MenuBuilder(context);
            MenuInflater inflater = new MenuInflater(context);
            inflater.inflate(R.menu.options_menu, menuBuilder);
    

    Solution 3:

    Without using custom adapter it is impossible to change the color of

     android.R.layout.simple_spinner_dropdown_item
    

    Better create a custom adapter and then you can change the color, testSixe, textStyle, etc.

  5. android - How do you change the textcolor of the list items in an AlertDialog
  6. Question:

    Hello I am trying to change the text color of the items in a list on a ListPreference pop up window. I have spent over an hour looking through all of the various style names but I can't find TextAppearance or anything that goes to this particular text. Thanks for your help!


    Solution 1:

    You can't and you shouldn't. *Preference uses styles from com.android.internal.R.styleable which might be changed by manufactures. The idea of using the default ones is that every preference screen in your device look alike.

    On the other hand you can try doing an Activity with android:theme="@android:style/Theme.Dialog" in your app's AndroidManifest and place a ListView styled as you want.

    Solution 2:

    I don't really know which kind of View use ListPreference, probably it's something like TextView. If so than you could make smth like:

    TextView textView;
    String myString;
    //....
    SpannableString spanString=new SpannableString(myString);
    spanString.setSpan(new ForegroundColorSpan(Color.RED), 0, myString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(spanString);
    

  7. android - Change MenuItem text color programmatically
  8. Question:

    So I have a menu item, that's defined as:

    <item
        android:id="@+id/action_live"
        android:title="@string/action_live"
        android:orderInCategory="1"
        app:showAsAction="ifRoom|withText" />
    

    It shows as text, as you can see below:

    Screenshot 1

    And I want to programmatically change the "LIVE" text color. I've searched for a while and I found a method:

    With globally defined:

    private Menu mOptionsMenu;
    

    and:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mOptionsMenu = menu;
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    

    I do:

    MenuItem liveitem = mOptionsMenu.findItem(R.id.action_live);
    SpannableString s = new SpannableString(liveitem.getTitle().toString());
    s.setSpan(new ForegroundColorSpan(Color.RED), 0, s.length(), 0);
    liveitem.setTitle(s);
    

    But nothing happens!

    If I do the same for an item of the overflow menu, it works:

    Screenshot 2

    Is there some limitation for app:showAsAction="ifRoom|withText" items? Is there any workaround?

    Thanks in advance.


    Solution 1:

    Bit late to the party with this one, but I spent a while working on this and found a solution, which may be of use to anyone else trying to do the same thing. Some credit goes to Harish Sridharan for steering me in the right direction.

    You can use findViewById(R.id.MY_MENU_ITEM_ID) to locate the menu item (provided that the menu had been created and prepared), and cast it to a TextView instance as suggested by Harish, which can then be styled as required.

    public class MyAwesomeActivity extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
    
        // Force invalidatation of the menu to cause onPrepareOptionMenu to be called
        invalidateOptionsMenu();
    }
    
    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
            ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); // Increase font size
        }
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean result = super.onPrepareOptionsMenu(menu);
        styleMenuButton();
        return result;
    }
    

    }

    The trick here is to force the menu to be invalidated in the activity's onCreate event (thereby causing the onPrepareMenuOptions to be called sooner than it would normally). Inside this method, we can locate the menu item and style as required.

    Solution 2:

    @RRP give me a clue ,but his solution does not work for me. And @Box give a another, but his answer looks a little not so cleaner. Thanks them. So according to them, I have a total solution.

    private static void setMenuTextColor(final Context context, final Toolbar toolbar, final int menuResId, final int colorRes) {
        toolbar.post(new Runnable() {
            @Override
            public void run() {
                View settingsMenuItem =  toolbar.findViewById(menuResId);
                if (settingsMenuItem instanceof TextView) {
                    if (DEBUG) {
                        Log.i(TAG, "setMenuTextColor textview");
                    }
                    TextView tv = (TextView) settingsMenuItem;
                    tv.setTextColor(ContextCompat.getColor(context, colorRes));
                } else { // you can ignore this branch, because usually there is not the situation
                    Menu menu = toolbar.getMenu();
                    MenuItem item = menu.findItem(menuResId);
                    SpannableString s = new SpannableString(item.getTitle());
                    s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), 0, s.length(), 0);
                    item.setTitle(s);
                }
    
            }
        });
    }
    

    Solution 3:

    In order to change the colour of menu item you can find that item, extract the title from it, put it in a Spannable String and set the foreground colour to it. Try out this code piece

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        MenuItem mColorFullMenuBtn = menu.findItem(R.id.action_submit); // extract the menu item here
    
        String title = mColorFullMenuBtn.getTitle().toString();
        if (title != null) {
            SpannableString s = new SpannableString(title);
            s.setSpan(new ForegroundColorSpan(Color.parseColor("#FFFFFF")), 0, s.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // provide whatever color you want here.
            mColorFullMenuBtn.setTitle(s);
        }
       return super.onCreateOptionsMenu(menu);
    }