Android中自定义控件TextSize属性问题

本文主要说明一个自定义控件添加TextSize属性的坑,刚刚从坑里面爬出来,写个随笔,记录一下;

*****************************************************************

今天自己在摸索Android的自定义控件,然后给控件添加了一个修改字体的属性:

    <declare-styleable name="BannerView">
        <attr name="indicator_item_text_size" format="dimension" />
    </declare-styleable>

然后在控件代码中的获取如下:

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        this.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        View rootView = LayoutInflater.from(context).inflate(R.layout.banner_view_layout, this, true);
        currentTV = (TextView) rootView.findViewById(R.id.introduce_tv);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BannerView, defStyleAttr, 0);
        indicatorTextSize = typedArray.getDimensionPixelSize(R.styleable.BannerView_indicator_item_text_size, 16);
        typedArray.recycle();

        currentTV.setTextSize(indicatorTextSize);
    }

欧了,启动app,结果,狗眼瞎了,文字字体比预计的要大很多,懵逼了!~

 

后面去问了一下Google爸爸,找到了这篇文章:https://zllbird.github.io/2015/11/23/android%E8%87%AA%E5%AE%9A%E4%B9%89%E5%B1%9E%E6%80%A7%E4%BD%BF%E7%94%A8/

终于知道为什么了:

上面那行代码改一下:

currentTV.setTextSize(TypedValue.COMPLEX_UNIT_PX, indicatorTextSize);

看一下截图,多么痛的领悟:

posted @ 2017-01-05 16:57  菜鸟_飞飞  阅读(6605)  评论(0编辑  收藏  举报