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

当前回答

假设你在values/styles.xml上有一个名为RedHUGEText的样式:

<style name="RedHUGEText" parent="@android:style/Widget.TextView">
    <item name="android:textSize">@dimen/text_size_huge</item>
    <item name="android:textColor">@color/red</item>
    <item name="android:textStyle">bold</item>
</style>

只是像往常一样在XML layout/your_layout.xml文件中创建你的TextView,让我们说:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content 
    android:text="FOO" />

在Activity的java代码中,你这样做:

TextView textViewTitle = (TextView) findViewById(R.id.text_view_title);
textViewTitle.setTextAppearance(this, R.style.RedHUGEText);

这对我很管用!它可以应用颜色,大小,重力等。我在Android API级别从8到17的手机和平板电脑上使用过,没有任何问题。请注意,在Android 23中,该方法已被弃用。context参数已经被删除,所以最后一行需要是:

textViewTitle.setTextAppearance(R.style.RedHUGEText);

支持所有API级别使用androidX TextViewCompat

TextViewCompat.setTextAppearance(textViewTitle, R.style.RedHUGEText)

记得……只有当文本的风格真的依赖于你的Java逻辑的条件,或者你正在用代码“快速”构建UI时,这才有用……如果没有,最好这样做:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content 
    android:text="FOO" 
    style="@style/RedHUGEText" />

你可以随心所欲!

其他回答

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

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

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

你可以试试这个

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