如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
如何设置TextView风格(粗体或斜体)在Java和不使用XML布局?
换句话说,我需要用Java编写android:textStyle。
当前回答
试着在TextView上设置粗体或斜体
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);
其他回答
这是我在配置了OnePlus Slate™字体的OnePlus 5T上唯一有效的功能:
textView.setTypeface(Typeface.create(textView.getTypeface(), useBold ? Typeface.BOLD : Typeface.NORMAL));
其他方法将使它在BOLD或NORMAL时回落到Roboto。
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)
最好的方法是在styles.xml中定义它
<style name="common_txt_style_heading" parent="android:style/Widget.TextView">
<item name="android:textSize">@dimen/common_txtsize_heading</item>
<item name="android:textColor">@color/color_black</item>
<item name="android:textStyle">bold|italic</item>
</style>
在TextView中更新
<TextView
android:id="@+id/txt_userprofile"
style="@style/common_txt_style_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/margin_small"
android:text="@string/some_heading" />
标准的方法是使用自定义样式。 除
在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" />
编程:
你可以通过编程方式使用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"
或者你可以设置你最喜欢的字体(从资产)。欲了解更多信息,请参阅链接