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

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


当前回答

在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));

其他回答

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


yourTextView.makeBold()

你可以这样做:

myTextView.setTypeface(null, Typeface.ITALIC);
myTextView.setTypeface(null, Typeface.BOLD_ITALIC);
myTextView.setTypeface(null, Typeface.BOLD);
myTextView.setTypeface(null, Typeface.NORMAL);

如果你想保留之前的字体,不想失去之前应用的字体,那么另一个选择:

myTextView.setTypeface(textView.getTypeface(), Typeface.NORMAL);      
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD);        
myTextView.setTypeface(textView.getTypeface(), Typeface.ITALIC);      
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); 

试着在TextView上设置粗体或斜体

textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);

你有两个选择:

选项1(只适用于粗体、斜体和下划线):

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(Html.fromHtml(s));

选项2:

使用可伸缩帆布;它更复杂,但您可以动态修改文本属性(不仅是粗体/斜体,还包括颜色)。

试试这个:

TextView textview = (TextView)findViewById(R.id.textview_idname);
textview.setTypeface(null,Typeface.BOLD);