【項目筆記】拿寬高前measure(widthMeasureSpec, heightMeasureSpec)的使用技巧


我們知道獲取寬高一般寫法是:

1         view.measure(0, 0);
2         view.getMeasuredHeight(); 

拿寬高前什么時候可以直接用measure(0, 0);而什么時候不能用measure(0, 0);

 

1.直接用measure(0, 0);

textview控件已經存在於布局文件里,例如:

1     <TextView
2         android:id="@+id/textView1"
3  android:layout_width="wrap_content"
4  android:layout_height="wrap_content"
5         android:text="TextView" />

則可以直接使用measure(0, 0); 因為我們不需要去判斷它的寬高模式,讓系統底層自己根據布局文件判斷。而什么時候不能用measure(0, 0);呢?請看第2點:

 

2.不能用measure(0, 0);

當textview控件不存在於布局文件里,也就是textview是我們用代碼生生地new出來的時候,只能先確定widthMeasureSpec和heightMeasureSpec,再調用measure(widthMeasureSpec, heightMeasureSpec),而widthMeasureSpec和heightMeasureSpec可以用MeasureSpec.makeMeasureSpec(size, mode);來生成。

例如我要一個textview,讓它寬度確定(match_parent),高度不確定(wrap_content),java代碼可以這么寫:

 1         TextView view = new TextView(UIUtils.getContext());
 2         view.setText(getData().des);// 設置文字
 3         view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);// 設置文字大小
 4 
 5 
 6         int widthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
 7                 MeasureSpec.EXACTLY);// 寬不變, 確定值, match_parent
 8         int heightMeasureSpec = MeasureSpec.makeMeasureSpec(2000,
 9                 MeasureSpec.AT_MOST);// 高度包裹內容, wrap_content;當包裹內容時,
10                                         // 參1表示尺寸最大值,暫寫2000, 也可以是屏幕高度
11 
12         // 開始測量
13         view.measure(widthMeasureSpec, heightMeasureSpec);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM