记一次setTextSize失效的问题的解决过程

概述

最近在忙着改已经上线产品的Bug,遇到了一个对于我来说很头疼的问题,因为一上来就走了弯路,卡了蛮长的时间未能解决,在这里特意记录一下。

问题描述

我自定义了一个很简单的textview,让它是正方形的view,代码如下:

public class SquareTextView extends AutoResizeTextView {

    public SquareTextView(Context context) {
        super(context);
    }

    public SquareTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SquareTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}

然后也没有多想,在代码里就设置了setTextSize,去动态设置这个textview的字体大小,发现没有效果。

问题解决

为此我进行了各种各样的尝试(一把辛酸泪),最终我在看文档的时候发现了这句话:

setTextSize
added in API level 1
void setTextSize (float size)
Set the default text size to the given value, interpreted as “scaled pixel” units. This size is adjusted based on the current density and user font size preference.

Note: if this TextView has the auto-size feature enabled than this function is no-op.

再强调一遍:

Note: if this TextView has the auto-size feature enabled than this function is no-op.

这句话提醒了我,是不是因为我设置了自定义的始终为正方形的textview,而导致动态代码设置字体大小失败呢。于是我使用了textview而不是我自定义的view,发现可以动态设置字体大小了。

总结

其实这个问题很简单,我之所以在这里特意记录就是为了提醒自己,也是提醒大家多去看文档,看官方文档,说不定其中的内容就会对我们有一些启发,这样可以避免很多坑,希望也能帮助到你~

你可能感兴趣的:(Android)