如何改变文本/字体设置在一个Android TextView?
例如,如何使文本加粗?
如何改变文本/字体设置在一个Android TextView?
例如,如何使文本加粗?
当前回答
在XML中
android:textStyle="bold" //only bold
android:textStyle="italic" //only italic
android:textStyle="bold|italic" //bold & italic
你只能使用特定的字体sans, serif和monospace通过xml, Java代码可以使用自定义字体
android:typeface="monospace" // or sans or serif
以编程方式(Java代码)
TextView textView = (TextView) findViewById(R.id.TextView1);
textView.setTypeface(Typeface.SANS_SERIF); //only font style
textView.setTypeface(null,Typeface.BOLD); //only text style(only bold)
textView.setTypeface(null,Typeface.BOLD_ITALIC); //only text style(bold & italic)
textView.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD);
//font style & text style(only bold)
textView.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD_ITALIC);
//font style & text style(bold & italic)
其他回答
在.xml文件中,设置
android:textStyle="bold"
将文本类型设置为粗体。
这很简单
setTypeface(Typeface.DEFAULT_BOLD);
在XML中
android:textStyle="bold" //only bold
android:textStyle="italic" //only italic
android:textStyle="bold|italic" //bold & italic
你只能使用特定的字体sans, serif和monospace通过xml, Java代码可以使用自定义字体
android:typeface="monospace" // or sans or serif
以编程方式(Java代码)
TextView textView = (TextView) findViewById(R.id.TextView1);
textView.setTypeface(Typeface.SANS_SERIF); //only font style
textView.setTypeface(null,Typeface.BOLD); //only text style(only bold)
textView.setTypeface(null,Typeface.BOLD_ITALIC); //only text style(bold & italic)
textView.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD);
//font style & text style(only bold)
textView.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD_ITALIC);
//font style & text style(bold & italic)
在我的情况下,通过string.xml通过html标签传递值..
<string name="your_string_tag"> <b> your_text </b></string> .
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())
}