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

当前回答

这对我有用

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

相反了

TextView.setTypeface(Typeface.DEFAULT_BOLD);

其他回答

使用数据绑定和Kotlin

@BindingAdapter("textViewStyle")
fun TextView.bindTextViewStyle(styleResourceId: Int) {
    TextViewCompat.setTextAppearance(this, styleResourceId)
}

XML

 <TextView
   android:layout_width="wrap_content"
   android:text="test text"
   bind:textViewStyle="@{styleResId}" />

• 科特林版本

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

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

这对我很有效

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);
            }

这对我有用

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

相反了

TextView.setTypeface(Typeface.DEFAULT_BOLD);