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

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

使用数据绑定和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}" />

你可以试试这个

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

如本文所述,目前不支持此功能。