如何改变文本/字体设置在一个Android TextView?

例如,如何使文本加粗?


当前回答

最好的方法是:

TextView tv = findViewById(R.id.textView);
tv.setTypeface(Typeface.DEFAULT_BOLD);

其他回答

要在layout.xml文件中这样做:

android:textStyle

例子:

android:textStyle="bold|italic"

程序上的方法是:

setTypeface(Typeface tf)

设置应显示文本的字体和样式。注意,并不是所有字体家族都有粗体和斜体变体,所以你可能需要使用setTypeface(Typeface, int)来获得你真正想要的外观。

你可以这样做

ty.setTypeface(Typeface.createFromAsset(ctx.getAssets(), "fonts/magistral.ttf"), Typeface.BOLD);
textView.setPaintFlags(textView.getPaintFlags() | Paint.FAKE_BOLD_TEXT_FLAG)

要移除,请使用

textView.setPaintFlags(textView.getPaintFlags() & ~Paint.FAKE_BOLD_TEXT_FLAG)

或者用Kotlin:

fun TextView.makeBold() {
    this.paintFlags = this.paintFlags or Paint.FAKE_BOLD_TEXT_FLAG
}

fun TextView.removeBold() {
    this.paintFlags = this.paintFlags and (Paint.FAKE_BOLD_TEXT_FLAG.inv())
}

最好的方法是:

TextView tv = findViewById(R.id.textView);
tv.setTypeface(Typeface.DEFAULT_BOLD);

在Kotlin中,我们可以在一行中完成

 TEXT_VIEW_ID.typeface = Typeface.defaultFromStyle(Typeface.BOLD)