如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
当前回答
你可以这样尝试:
<string name="title"><u><b><i>Your Text</i></b></u></string>
其他回答
很简单,如果你想让文本加粗。 将这一行写在布局中的文本视图属性中
android:textStyle="bold"
使用textView。setTypeface(字体tf, int风格);设置TextView的样式属性。有关更多信息,请参阅开发人员文档。
正如这里所解释的,如果你需要在你的样式文本资源中使用参数,你必须转义开括号
<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);
你有两个选择:
选项1(只适用于粗体、斜体和下划线):
String s = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!"
TextView tv = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);
tv.setText(Html.fromHtml(s));
选项2:
使用可伸缩帆布;它更复杂,但您可以动态修改文本属性(不仅是粗体/斜体,还包括颜色)。
这是我在配置了OnePlus Slate™字体的OnePlus 5T上唯一有效的功能:
textView.setTypeface(Typeface.create(textView.getTypeface(), useBold ? Typeface.BOLD : Typeface.NORMAL));
其他方法将使它在BOLD或NORMAL时回落到Roboto。