如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
当前回答
基于样式选择标准,最简单的方法是:
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));
其他回答
正如这里所解释的,如果你需要在你的样式文本资源中使用参数,你必须转义开括号
<resources>
<string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</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.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);
编程:
你可以通过编程方式使用setTypeface()方法:
下面是默认字体的代码
textView.setTypeface(null, Typeface.NORMAL); // for Normal Text
textView.setTypeface(null, Typeface.BOLD); // for Bold only
textView.setTypeface(null, Typeface.ITALIC); // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic
如果你想设置自定义字体:
textView.setTypeface(textView.getTypeface(), Typeface.NORMAL); // for Normal Text
textView.setTypeface(textView.getTypeface(), Typeface.BOLD); // for Bold only
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC); // for Italic
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); // for Bold and Italic
XML:
你可以直接在<TextView />的XML文件中设置如下:
android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"
或者你可以设置你最喜欢的字体(从资产)。欲了解更多信息,请参阅链接
试试这个:
TextView textview = (TextView)findViewById(R.id.textview_idname);
textview.setTypeface(null,Typeface.BOLD);