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

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


当前回答

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

android:textStyle="bold"

其他回答

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

android:textStyle="bold"
TextView text = (TextView)findViewById(R.layout.textName);
text.setTypeface(null,Typeface.BOLD);

在AndroidX中使用简化标签时,请考虑使用HtmlCompat.fromHtml()

String s = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!"    
TextView tv = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);
tv.setText(HtmlCompat.fromHtml(s, FROM_HTML_MODE_LEGACY));

这是我在配置了OnePlus Slate™字体的OnePlus 5T上唯一有效的功能:

textView.setTypeface(Typeface.create(textView.getTypeface(), useBold ? Typeface.BOLD : Typeface.NORMAL));

其他方法将使它在BOLD或NORMAL时回落到Roboto。

它会是

yourTextView.setTypeface(null,Typeface.DEFAULT_BOLD);

和斜体应能与替换字体。DEFAULT_BOLD与字体。

让我知道它是如何工作的。