TextView isBold always returns NORMAL

2019-07-19 07:52发布

问题:

I am setting Typeface of a textview like this

textView.setTypeface(tf_roboto_medium, Typeface.BOLD);

When I check the style using this command, it is evaluated true.

if (textView.getTypeface().getStyle() == Typeface.NORMAL) {
// always here
}
else {
// never here
}

[EDIT] Here is my xml content for the TextView

<TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:text="Train"
                android:textColor="#777777"
                android:gravity="bottom|center"
                android:singleLine="true"
                android:id="@+id/txt_train"
                android:layout_gravity="left"
                android:layout_weight="15"
                android:textSize="32px"
                android:onClick="onTrainClick"
                android:clickable="true" />

What am I doing wrong?

PS : I have read other posts asking for the same thing. None of them seems to work for me. Thus the quesiton

回答1:

Try one of these this:

  1. if (textView.getTypeface().isBold()) {
  2. if ((textView.getTypeface().getStyle() & Typeface.BOLD) > 0) {

From what I see there is a bit mask used for font styles. Normal == 0 so there can be problems with 0 & 0



回答2:

You can do a string:

<string name="train"><b>Train</b></string>

And then set:

android:text="@string/train"