美文网首页
Android 中的粗体:怎么动态的设置粗体?怎么设置中粗

Android 中的粗体:怎么动态的设置粗体?怎么设置中粗

作者: MiBoy | 来源:发表于2020-06-27 22:25 被阅读0次

怎么动态设置粗体:

Android中的粗体大家都知道怎么设置,就是在 xml 中设置一个textStyle,但怎么动态的设置粗体呢,Android 的Textview中没有直接设置setTextBold这样的API,我这有两个办法去解决:

1.获取TextView的Paint,paint 中有个方法是setFakeBoldText,代码演示就是

  mTextView.getPaint().setFakeBoldText(true);

这个达到的效果是和设置 textStyle效果一致。

2.通过setTypeface( Typeface tf, @Typeface.Style int style),看下Typeface.Style的结构

   /** @hide */
    @IntDef(value = {NORMAL, BOLD, ITALIC, BOLD_ITALIC})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Style {}

是不是很熟悉啊,这不就是对应的textStyle中的三个参数吗

代码演示就是:

  mText.setTypeface(null, Typeface.BOLD);

咱们看一下源码

public void setTypeface(@Nullable Typeface tf, @Typeface.Style int style) {
        if (style > 0) { 
            if (tf == null) {
                tf = Typeface.defaultFromStyle(style); //typeface 是可以为null的,为null 就用默认的
            } else {
                tf = Typeface.create(tf, style);
            }

            setTypeface(tf);// 调用了 重载的函数,里面主要是把tf 传入到 textpaint里面操作
            // now compute what (if any) algorithmic styling is needed
            int typefaceStyle = tf != null ? tf.getStyle() : 0;
            int need = style & ~typefaceStyle;
            mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);// 其实和方法一殊途同归
            mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
        } else {
            mTextPaint.setFakeBoldText(false);
            mTextPaint.setTextSkewX(0);
            setTypeface(tf);
        }
    }

其实上面整体方法的思想还是通过 TextView里面的TextPaint 去设置 。

怎能设置中粗

我在开发的过程中,总会遇到设计给出的设置粗体和中粗的字重,一开始我们都以为中粗也是粗体,都用的 BOLD 的样式,但是经过对比,中粗比常规字体要粗,比粗体要细。那么要设置这个就要用到 fontFamily

    android:fontFamily="sans-serif-medium"
 Typeface typeface = Typeface.create("sans-serif-medium", 0);
 mText.setTypeface(typeface);

参考链接:https://blog.csdn.net/yuanxw44/article/details/80019501

相关文章

  • Android 中的粗体:怎么动态的设置粗体?怎么设置中粗

    怎么动态设置粗体: Android中的粗体大家都知道怎么设置,就是在 xml 中设置一个textStyle,但怎么...

  • TextView

    设置粗体在xml文件中使用Android:textStyle="bold" 可以将英文设置成粗体,但是不能将中文设...

  • 问题

    1,header的字体是粗体怎么设置? 2,header的“更多产品”的性质怎么设置? 3,button的边框和百...

  • 咋个玩法

    设置个标题试试 看起来不错 粗体怎么玩?粗体怎么玩?斜体怎么玩?这有什么用? 这个引用功能不错 来个两行看看效果 ...

  • Typeface 和 TypeStyle

    如何为 TextView 设置粗体?在 XML 文件中使用属性 android:typeface 来设置属性但是可...

  • 安卓设置粗体

    因为要在一个页面的多个地方显示粗体,默认粗体有点难看,而且UI要求是SemiBold 半粗体,所以自己调了一下。在...

  • Android之TextView通过代码设置/取消文字加粗

    在xml中设置TextView的粗体是使用textStyle="bold"来实现的,但是如果要在代码里动态的改变状...

  • TextView基本学习

    TextView如何产生丰富的文本。 显示文本 设置颜色和字体 设置大小号 设置小号 设置斜体,粗体 链接地址 插...

  • EditText属性

    注:本文是对网上一些方法的整理,以便查阅之用 易理解属性 粗体设置 android:textStyle=”bold...

  • TextView、EditText属性简介

    字体粗体设置: TextView的其他不常用属性: 给textView加下划线方法: 字体其他设置方法: 设置输入...

网友评论

      本文标题:Android 中的粗体:怎么动态的设置粗体?怎么设置中粗

      本文链接:https://www.haomeiwen.com/subject/ffnvfktx.html