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

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


当前回答

试试这个:

TextView textview = (TextView)findViewById(R.id.textview_idname);
textview.setTypeface(null,Typeface.BOLD);

其他回答

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

标准的方法是使用自定义样式。 除

在styles.xml中添加以下内容。

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="MyApp.TextAppearance.LoginText">
    <item name="android:textStyle">bold|italic</item>
</style>

应用此样式到你的TextView如下。

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/MyApp.TextAppearance.LoginText" />

很简单,如果你想让文本加粗。 将这一行写在布局中的文本视图属性中

android:textStyle="bold"

你可以这样做:

myTextView.setTypeface(null, Typeface.ITALIC);
myTextView.setTypeface(null, Typeface.BOLD_ITALIC);
myTextView.setTypeface(null, Typeface.BOLD);
myTextView.setTypeface(null, Typeface.NORMAL);

如果你想保留之前的字体,不想失去之前应用的字体,那么另一个选择:

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

在AndroidX中使用简化标签时,请考虑使用HtmlCompat.fromHtml()

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(HtmlCompat.fromHtml(s, FROM_HTML_MODE_LEGACY));