如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
当前回答
因为我想使用自定义字体,只有几个答案的连接为我工作。显然,设置在我的布局.xml像android:textStlyle="斜体"被AOS忽略。所以最后我不得不这样做: 在strings.xml中,目标字符串声明为:
<string name="txt_sign"><i>The information blah blah ...</i></string>
然后在代码中:
TextView textSign = (TextView) findViewById(R.id.txt_sign);
FontHelper.setSomeCustomFont(textSign);
textSign.setTypeface(textSign.getTypeface(), Typeface.ITALIC);
我没有尝试Spannable选项(我认为必须工作),但是
textSign.setText(Html.fromHtml(getString(R.string.txt_sign)))
没有效果。同样,如果我从strings.xml中删除斜体标记,只留下setTypeface(),它也没有任何影响。棘手的安卓…
其他回答
正如这里所解释的,如果你需要在你的样式文本资源中使用参数,你必须转义开括号
<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);
AppCompatTextView text =(AppCompatTextView)findViewById(R.layout.appCompatTextView1);
text.setTypeface(null,Typeface.BOLD);
使用上述方法以编程方式设置字体。
基于样式选择标准,最简单的方法是:
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));
这是我在配置了OnePlus Slate™字体的OnePlus 5T上唯一有效的功能:
textView.setTypeface(Typeface.create(textView.getTypeface(), useBold ? Typeface.BOLD : Typeface.NORMAL));
其他方法将使它在BOLD或NORMAL时回落到Roboto。
编程:
你可以通过编程方式使用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"
或者你可以设置你最喜欢的字体(从资产)。欲了解更多信息,请参阅链接