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

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


当前回答

编程:

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

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

其他回答

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

现在设置textview属性..

text.setTypeface(null, Typeface.BOLD);  //-- for only bold the text
text.setTypeface(null, Typeface.BOLD_ITALIC);  //-- for  bold & italic the text
text.setTypeface(null, Typeface.ITALIC);  // -- for  italic the text

试试这个:

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

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

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)