在xml中設置字體:
<!-- <TextView-->
<!-- android:textSize="@dimen/sp_9"android:layout_height="@dimen/dp_14" -->
然后想著不這么設置,想著代碼中動態設置字體大小,改為如下:
setTextSize(context.getResources().getDimension(R.dimen.sp_9));//設置字體大小RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int)context.getResources().getDimension(R.dimen.dp_14),(int)context.getResources().getDimension(R.dimen.dp_14)); //設置寬高
想著應該沒問題吧,結果動態代設置的字體比xml中設置的大很多,而寬高確沒變化
原因:
在XML中設置android:textSize="@dimen/sp_9"和?android:layout_height="@dimen/dp_14" 時,系統會自動解析成sp和dp.
但是getDimension()會自動把數值解析成xp單位,因為view的寬高本來接受的就是xp,所以不會變化,但是 setTextSize接受的單位默認是sp。相當于getDimension()把sp轉成xp,會放大,setTextSize又會將轉換后的值變成xp,又放大了
修改:將Textsie接受的默認參數修改成xp就可以了
setTextSize(TypedValue.COMPLEX_UNIT_PX,context.getResources().getDimension(R.dimen.sp_9));