是否有一种方法来设置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" />

当前回答

这对我很有效

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

or

textview.setTypeface(Typeface.DEFAULT_BOLD);

其他回答

textview.setTypeface(Typeface.DEFAULT_BOLD);

setTypeface是属性文本样式。

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

textview.setTypeface(textview.getTypeface(), Typeface.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);
    }
}

这对我有用

msg.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
OR
TextView.setTypeface(msg.getTypeface(),Typeface.NORMAL);

相反了

TextView.setTypeface(Typeface.DEFAULT_BOLD);

• 科特林版本

保留当前字体和文本样式:

textView.apply {
    setTypeface(typeface, Typeface.NORMAL)
    // or
    setTypeface(typeface, Typeface.BOLD)
    // or
    setTypeface(typeface, Typeface.ITALIC)
    // or
    setTypeface(typeface, Typeface.BOLD_ITALIC)
}