【學習筆記】拿寬高前measure(widthMeasureSpec, heightMeasureSpec)的提示

來源:互聯網
上載者:User

標籤:

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

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

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

 

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

textview控制項已經存在於布局檔案裡,例如:

1     <TextView2         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);

 

【學習筆記】拿寬高前measure(widthMeasureSpec, heightMeasureSpec)的提示

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.