You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Android中TextView设置为比默认粗体更粗的效果

实现TextView自定义加粗效果的可行方案

方案1:通过画笔描边实现快速伪加粗

适合临时需要少量增加字重的场景,不需要引入额外资源

  • 代码动态设置示例:
// Kotlin 实现
textView.paint.apply {
    isFakeBoldText = true
    style = Paint.Style.FILL_AND_STROKE
    strokeWidth = 0.5f // 可调整数值控制加粗程度,单位为px,建议转换为dp适配多屏幕
}
// Java 实现
textView.getPaint().setFakeBoldText(true);
textView.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);
textView.getPaint().setStrokeWidth(0.5f);

注意:strokeWidth数值不宜超过1f,否则会导致文字边缘变圆润、字体变形,普通需求下0.3~0.8f即可达到比默认粗体更粗的效果。

如果需要全局生效,可以自定义TextView子类,在onMeasure或者onDraw方法中统一配置画笔属性。

方案2:引入多字重自定义字体

适合对显示效果要求高、需要固定超粗字重的场景,效果最自然无变形
Android 8.0及以上支持原生字重配置,你可以下载对应字体的不同字重版本(比如Roboto的900字重、思源黑体的Heavy字重等),放到res/font目录下,创建字体家族配置文件:

<!-- res/font/custom_font_family.xml -->
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font android:font="@font/custom_regular" android:fontWeight="400" android:fontStyle="normal" />
    <font android:font="@font/custom_bold" android:fontWeight="700" android:fontStyle="normal" />
    <font android:font="@font/custom_black" android:fontWeight="900" android:fontStyle="normal" />
</font-family>

在XML中直接指定字重即可:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="超粗显示文本"
    android:fontFamily="@font/custom_font_family"
    android:textFontWeight="900" />

低版本兼容可以直接在代码中设置对应字重的字体:

textView.typeface = ResourcesCompat.getFont(context, R.font.custom_black)

提示:使用第三方商用字体前请确认授权合规,避免侵权风险。

方案3:使用Span实现部分文本加粗

如果只需要给TextView内的部分内容设置超粗效果,可以通过自定义Span修改对应文本的画笔属性:

val content = SpannableString("只有这段文字中的「超粗部分」需要特殊加粗")
// 对应下标根据实际文本内容调整
content.setSpan(object : StyleSpan(Typeface.BOLD) {
    override fun updateDrawState(ds: TextPaint) {
        super.updateDrawState(ds)
        ds.style = Paint.Style.FILL_AND_STROKE
        ds.strokeWidth = 0.6f
    }
}, 8, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
textView.text = content

内容的提问来源于stack exchange,提问作者Vinh Hung Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:54:05