如何改变文本/字体设置在一个Android TextView?
例如,如何使文本加粗?
如何改变文本/字体设置在一个Android TextView?
例如,如何使文本加粗?
当前回答
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())
}
其他回答
从XML中,您可以将textStyle设置为粗体,如下所示
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bold text"
android:textStyle="bold"/>
您可以像下面这样通过编程方式将TextView设置为粗体
textview.setTypeface(Typeface.DEFAULT_BOLD);
在Kotlin中,我们可以在一行中完成
TEXT_VIEW_ID.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
你可以这样做
ty.setTypeface(Typeface.createFromAsset(ctx.getAssets(), "fonts/magistral.ttf"), Typeface.BOLD);
在.xml文件中,设置
android:textStyle="bold"
将文本类型设置为粗体。
在理想的情况下,你应该在你的布局XML定义中设置文本样式属性,就像这样:
<TextView
android:id="@+id/TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"/>
通过使用setTypeface方法,有一个简单的方法可以在代码中动态地实现相同的结果。你需要传递一个Typeface类的对象,它将描述TextView的字体样式。因此,要实现与上面XML定义相同的结果,您可以执行以下操作:
TextView Tv = (TextView) findViewById(R.id.TextView);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
Tv.setTypeface(boldTypeface);
第一行将创建对象表单预定义的样式(在本例中为字体。BOLD,但还有更多预定义的)。一旦我们有了一个字体实例,我们就可以在TextView上设置它。这就是我们的内容将显示在我们定义的样式上。
我希望这对你有很大帮助。欲了解更多信息,请访问
http://developer.android.com/reference/android/graphics/Typeface.html