Home » Android » android – set typeface of text view to Typeface.NORMAL doesn't have any effect, why?

android – set typeface of text view to Typeface.NORMAL doesn't have any effect, why?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have listeners for ExpandableListView for group collapsed and expanded:

// There is a text view on group layout, no problem there.
    @Override
    public void onGroupCollapse(int groupPosition) {
        // this callback is triggered, however, once the textView is BOLD by onGroupExpanded, the textView is not set back to normal, seems this line of code does nothing...WHY?
        textView.setTypeface(textView.getTypeface(), Typeface.NORMAL);
    }

    @Override
    public void onGroupExpand(int groupPosition) {
        // it works fine
        textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
    }

As you can see above, I have a textView in group layout, when group is expanded, I bold the textView, if collapsed, I try to set it back to unbold by Typeface.NORMAL.

Both callbacks are triggered correctly, however, once the textView is BOLD by onGroupExpanded(...) callback, the textView is not set back to NORMAL when onGroupCollapse(...) is triggered afterwards. Seems the line of code in onGroupCollapsed(...)does nothing…WHY?

(Again, onGroupCollapse(...) is triggered. No problem there!)

How to&Answers:

Use this instead:

textView.setTypeface(null, Typeface.NORMAL);

you need to put null to drop the other typefaces (in your case Bold). How I understand it one text view can have multiple typesfaces, like for example italic+bold etc. and the first parameter is to indicate if you want to keep those or not. So basically your previous code kept BOLD and added NORMAL, and BOLD won 😉

see also related answer and comments here https://stackoverflow.com/a/6200841/2399024

Answer:

If you use android:fontFamily on this TextView then I am pretty sure

textView.setTypeface(null, Typeface.NORMAL);

will change to the default font. Another way to do this is:

textView.setTypeface(Typeface.create(textView.getTypeface(), Typeface.NORMAL));

The original problem is that TextView’s setTypeface with the style oddly skips over some stuff if the style is NORMAL. I’ve tested this on one version, and it works.