是否有一种方法来设置TextView的textStyle属性编程?似乎没有setTextStyle()方法。

需要明确的是,我不是在谈论视图/小部件样式!我说的是以下几点:

<TextView
  android:id="@+id/my_text"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Hello World"
  android:textStyle="bold" />

当前回答

由于setTextAppearance(resId)仅适用于API 23及以上版本,请使用:

TextViewCompat。setTextAppearance (textViewGoesHere渣油)

该方法在内部实现如下:

public static void setTextAppearance(@NonNull TextView textView, @StyleRes int resId) {
    if (Build.VERSION.SDK_INT >= 23) {
        textView.setTextAppearance(resId);
    } else {
        textView.setTextAppearance(textView.getContext(), resId);
    }
}

其他回答

这对我很有效

textview.setTypeface(textview.getTypeface(), Typeface.BOLD);

or

textview.setTypeface(Typeface.DEFAULT_BOLD);

你可以试试这个

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                textView.setTextAppearance(R.style.Lato_Bold);
            } else {
                textView.setTextAppearance(getActivity(), R.style.Lato_Bold);
            }

由于setTextAppearance(resId)仅适用于API 23及以上版本,请使用:

TextViewCompat。setTextAppearance (textViewGoesHere渣油)

该方法在内部实现如下:

public static void setTextAppearance(@NonNull TextView textView, @StyleRes int resId) {
    if (Build.VERSION.SDK_INT >= 23) {
        textView.setTextAppearance(resId);
    } else {
        textView.setTextAppearance(textView.getContext(), resId);
    }
}

搜索setTextAppearance或setTextTypeface。在stackoverflow上也有类似的问题:如何在运行时改变TextView的样式

textview.setTypeface(Typeface.DEFAULT_BOLD);

setTypeface是属性文本样式。

正如Shankar V补充的那样,为了保留之前设置的字体属性,你可以使用:

textview.setTypeface(textview.getTypeface(), Typeface.BOLD);