如何通过编程方式设置TextView的字体粗细?无需创建新字体
如何在不创建新字体的情况下修改TextView的字体粗细?
你可以通过以下两种方式实现,无需创建新字体文件:
1. 在XML布局中直接设置
- 基础粗体/斜体:使用
android:textStyle属性,可选值包括normal(常规)、bold(粗体)、italic(斜体),也可以组合使用如bold|italic:
<TextView android:id="@+id/my_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="示例文本" android:textStyle="bold" />
- 自定义字重(Android 8.0/API 26及以上):使用
android:fontWeight属性,取值范围为100-900(100最细,900最粗,400为常规,700对应标准粗体):
<TextView android:id="@+id/my_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="半粗体示例" android:fontWeight="600" />
2. 在代码中动态设置
Java 实现
- 设置标准粗体:
TextView textView = findViewById(R.id.my_text); // 保留原字体,仅修改样式为粗体 textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
- 自定义字重(Android 9.0/API 28及以上):
TextView textView = findViewById(R.id.my_text); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { // 保留原字体,设置字重为600 textView.setTypeface(textView.getTypeface(), Typeface.NORMAL, 600); } else { // 低版本 fallback 到标准粗体 textView.setTypeface(textView.getTypeface(), Typeface.BOLD); }
Kotlin 实现
- 设置标准粗体:
val textView = findViewById<TextView>(R.id.my_text) textView.setTypeface(textView.typeface, Typeface.BOLD)
- 自定义字重(Android 9.0/API 28及以上):
val textView = findViewById<TextView>(R.id.my_text) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { textView.setTypeface(textView.typeface, Typeface.NORMAL, 600) } else { textView.setTypeface(textView.typeface, Typeface.BOLD) }
注意事项
- 自定义字重的效果依赖于当前TextView使用的字体是否支持对应的字重等级,如果字体本身没有该字重的变体,设置后不会有视觉变化。
- 低版本系统(API <26)仅支持
textStyle的基础样式切换,无法自定义字重。
内容的提问来源于stack exchange,提问作者Yan
相关产品推荐
相关产品推荐

