Remove Bold from textview without changing other a

2019-02-14 08:57发布

I use setTypeface to set a text bold (or italics, or other of the typeface attributes)

TextView tv = findViewById(R.id.label);
...
tv.setTypeface(null,Typeface.BOLD);
...

How do I remove only the bold attribute, without changing other attributes that might have been set so far?

3条回答
叼着烟拽天下
2楼-- · 2019-02-14 09:12

this chunk of code removed the old Typeface setTypeface(null,Typeface.NORMAL);

For keeping the old you should call

setTextViewStyle(textView, isBold);

private void setTextViewStyle(TextView view, boolean isBold){
    if (view == null)
        return;

    // if old typeface is null create new Typeface bold or def
    Typeface oldTypeface = view.getTypeface() != null ? view.getTypeface() :
            (isBold ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);

    view.setTypeface(
            Typeface.create(oldTypeface, isBold ? Typeface.BOLD : Typeface.NORMAL)
    );
}
查看更多
戒情不戒烟
3楼-- · 2019-02-14 09:28
tv.setTypeface(null,Typeface.NORMAL);

This would set the style back to normal without changing color or size.

But you can't mix bold/italic/underline text this way. If you specify BOLD, all of the text will be bold. If you want to mix the style of the text I suggest using HTML to style the text, and then use the following code.

tv.setText(Html.fromHtml(yourStringAsHtml));
查看更多
对你真心纯属浪费
4楼-- · 2019-02-14 09:35

like me, if you want to preserve the custom font you have set to the TextView and just remove BOLD attribute, you can try

tv.getPaint().setFakeBoldText(false)

Doing following removed the custom font I had set to the TextView.

tv.setTypeface(null,Typeface.NORMAL);
查看更多
登录 后发表回答