本文主要說明一個自定義控件添加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);
看一下截圖,多么痛的領悟:
