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

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


当前回答

正如这里所解释的,如果你需要在你的样式文本资源中使用参数,你必须转义开括号

<resources>
<string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string>
</resources>

然后调用formatHtml(string)

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);

其他回答

试试这个:

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

保持以前的字体

textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)

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

基于样式选择标准,最简单的方法是:

String pre = "", post = "";

if(isBold){
    pre += "<b>"; post += "</b>";
}
if(isItalic){
    pre += "<i>"; post += "</i>";
}
if(isUnderline){
    pre += "<u>"; post += "</u>";
}

textView.setText(Html.fromHtml(pre + editText.getText().toString()+ post));
// you can also use it with EidtText
editText.setText(Html.fromHtml(pre + editText.getText().toString()+ post));

使用textView。setTypeface(字体tf, int风格);设置TextView的样式属性。有关更多信息,请参阅开发人员文档。