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

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


当前回答

试试这个:

textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);

其他回答

你有两个选择:

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

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

1)你可以用字体设置。 2)你可以直接在strings.xml中使用(在你的values文件夹中) 3)你可以String myNewString = " This is my bold text This is my italics String This is my underscore String .

基于样式选择标准,最简单的方法是:

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));
TextView text = (TextView)findViewById(R.layout.textName);
text.setTypeface(null,Typeface.BOLD);

试试这个:

textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);