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",就是固定值,注意:返回的值都是px單位.

如果你設置了"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()

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後的不一樣。 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章