如何在Java中设置TextView
的样式(粗体或斜体),而不使用XML布局?
换句话说,我需要用Java写android:textStyle
。
TextView text = (TextView)findViewById(R.layout.textName);
text.setTypeface(null,Typeface.BOLD);
尝试使用以下代码通过Java设置TextView
的样式:
txt1.setTypeface(null,Typeface.BOLD_ITALIC);
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)
试试这个:
TextView textview = (TextView)findViewById(R.id.textview_idname);
textview.setTypeface(null,Typeface.BOLD);
<string name="title"><u><b><i>Your Text</i></b></u></string>
标准做法是使用自定义样式。
在 styles.xml
中添加以下内容。
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="MyApp.TextAppearance.LoginText">
<item name="android:textStyle">bold|italic</item>
</style>
TextView
,请按如下方式进行。<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/MyApp.TextAppearance.LoginText" />
如Android开发者字符串资源所述,如果您需要在样式化文本资源中使用参数,则必须转义打开括号。
<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);
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));
方法一:
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);