如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?

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


当前回答

它会是

yourTextView.setTypeface(null,Typeface.DEFAULT_BOLD);

和斜体应能与替换字体。DEFAULT_BOLD与字体。

让我知道它是如何工作的。

其他回答

你有两个选择:

选项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:

使用可伸缩帆布;它更复杂,但您可以动态修改文本属性(不仅是粗体/斜体,还包括颜色)。

编程:

你可以通过编程方式使用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"

或者你可以设置你最喜欢的字体(从资产)。欲了解更多信息,请参阅链接

它会是

yourTextView.setTypeface(null,Typeface.DEFAULT_BOLD);

和斜体应能与替换字体。DEFAULT_BOLD与字体。

让我知道它是如何工作的。

因为我想使用自定义字体,只有几个答案的连接为我工作。显然,设置在我的布局.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(),它也没有任何影响。棘手的安卓…

使用textView。setTypeface(字体tf, int风格);设置TextView的样式属性。有关更多信息,请参阅开发人员文档。