12.7 Android-以编程方式设置TextView TextStyle? | Java Debug 笔记

639 阅读1分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看<活动链接>

提问:如何在Android中以编程方式设置TextView TextStyle?

有没有办法以编程方式设置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" />

回答1:

textview.setTypeface(Typeface.DEFAULT_BOLD);

如果要保留之前的属性的话,你可以

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

回答2:

假设您在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" />