如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?

换句话说,我需要用Java编写android:textStyle。


当前回答

//leveraging the extension functions
fun TextView.makeBold(){
    this.setTypeface(this.typeface,Typeface.BOLD)
}


yourTextView.makeBold()

其他回答

使用textView。setTypeface(字体tf, int风格);设置TextView的样式属性。有关更多信息,请参阅开发人员文档。

很简单,如果你想让文本加粗。 将这一行写在布局中的文本视图属性中

android:textStyle="bold"
textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);

保持以前的字体

textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)

标准的方法是使用自定义样式。 除

在styles.xml中添加以下内容。

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="MyApp.TextAppearance.LoginText">
    <item name="android:textStyle">bold|italic</item>
</style>

应用此样式到你的TextView如下。

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/MyApp.TextAppearance.LoginText" />

在我的例子中:

1 -设置文本

2 -设置字体

holder.title.setText(item.nome);
holder.title.setTypeface(null, Typeface.BOLD);