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" />

原文由 Jake Wilson 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 986
2 个回答
textview.setTypeface(Typeface.DEFAULT_BOLD);

setTypeface 是属性 textStyle。

正如 Shankar V 所补充的,要保留之前设置的字体属性,您可以使用:

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

原文由 Raz 发布,翻译遵循 CC BY-SA 3.0 许可协议

假设您在 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 开始,该方法已被弃用。上下文参数已被删除,因此最后一行需要是:

 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" />

您可以随心所欲!

原文由 Oscar Salguero 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题