如何设置TextView的文本样式,例如加粗、斜体?

957

如何在Java中设置TextView的样式(粗体或斜体),而不使用XML布局?

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

29个回答

10
TextView text = (TextView)findViewById(R.layout.textName);
text.setTypeface(null,Typeface.BOLD);

10

尝试使用以下代码通过Java设置TextView的样式:

txt1.setTypeface(null,Typeface.BOLD_ITALIC);

8
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)

7
使用textView.setTypeface(Typeface tf, int style);方法来设置TextView的样式属性。详细信息请参见开发人员文档

6

试试这个:

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

4
你可以像这样尝试:
<string name="title"><u><b><i>Your Text</i></b></u></string>

4

标准做法是使用自定义样式。

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" />

4

Android开发者字符串资源所述,如果您需要在样式化文本资源中使用参数,则必须转义打开括号。

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

4
根据样式选择标准,您可以采取最简单的方法:
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));

4
您可以采用以下一种方式来实现:

方法一:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接