如何设置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 text = (TextView)findViewById(R.layout.textName);
text.setTypeface(null,Typeface.BOLD);
TextView text = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);

现在设置textview属性..

text.setTypeface(null, Typeface.BOLD);  //-- for only bold the text
text.setTypeface(null, Typeface.BOLD_ITALIC);  //-- for  bold & italic the text
text.setTypeface(null, Typeface.ITALIC);  // -- for  italic the text

你可以这样尝试:

<string name="title"><u><b><i>Your Text</i></b></u></string>

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

AppCompatTextView text =(AppCompatTextView)findViewById(R.layout.appCompatTextView1);
text.setTypeface(null,Typeface.BOLD);

使用上述方法以编程方式设置字体。