Android 關於view的getLayoutParams().width,getWidth(),getMeasuredWidth();


習慣了使用xml的布局方式,當動態布局的時候就有許多疑點,記錄一下,幫助我這老頭一樣的記憶力.


網上也有許多解析這getLayoutParams().width,getWidth(),getMeasuredWidth();三種方式的獲取區別,參考並理解了下:


getLayoutParams().width:

這里順便提下,LayoutParams,每個view都需要一個LayoutParams,告訴父容器的一些規則和方式,這時候該view的LayoutParams要與父容器的LayoutParam相相對應,比如該view的父容器使用的LinearLayout.LayoutParam,該view的布局類型也要對應着LinearLayout.LayoutParam,不然的話回報類型轉換錯誤.好了LayoutParam就提到這里.

getLayoutParams().width獲取的寬度是條件是你地xml中定義該view的時候,Android:widt="150dp",就是固定值,如果你設置了"match_parent","wrap_content",返回的值是-1,其實是定義的常量:


public static final int FILL_PARENT = -1;

public static final int MATCH_PARENT = -1;

public static final int WRAP_CONTENT = -2;
 
        
getLayoutParams().width返回的是該view向父view請求的最大寬度,不是view實際繪畫的寬度.怎么說呢,其實應該是接近實際寬度.

getWidth()大多人使用的時候返回都是0,因為在oncreat()中view還沒被繪制的,在制onWindowFocusChanged()開始繪制的,getWidth()獲取的就是該view的實際寬度.所以要想獲取該高度在oncreat():



 ViewTreeObserver vto2 = firstAd.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                firstAd.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                RelativeLayout.LayoutParams lp= (RelativeLayout.LayoutParams)  firstAd.getLayoutParams();                             }         }); 

getMeasuredWidth()

在onMeasure()執行完后才會有值 ,該方法就是getLayoutParams().width所說的父容器寄給的最大寬度.
View的大小由width和height決定。一個View實際上同時有兩種width和height值 
• 第一種是measure width和measure height。他們定義了view想要在父View中占用多少width和height(詳情見Layout)。measured height和width可以通過getMeasuredWidth() 和 getMeasuredHeight()獲得。 
• 
• 第二種是width和height,有時候也叫做drawing width和drawing height。這些值定義了view在屏幕上繪制和Layout完成后的實際大小。這些值有可能跟measure width和height不同。width和height可以通過getWidth()和getHeight()獲得。 
這兩個方法所獲取的width和height可能跟實際draw后的不一樣。 

 


免責聲明!

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



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