Return the width of the your view.
Returns
The width of your view, in pixels.
源代碼:
public final int getWidth() {
return mRight - mLeft;
}
getwidth返回的是右邊坐標減輕坐標減去左邊坐標,這要在布局之後才能確定它們的坐標,也就是說在布局後才能調用getwidth來獲取。所以getWidth()獲得的寬度是View在設定好布局後整個View的寬度。
getMeasuredWidth()
Return the full width measurement information for this view as computed by the most recent call to measure(int, int). This result is a bit mask as defined byMEASURED_SIZE_MASK and MEASURED_STATE_TOO_SMALL. This should be used during measurement and layout calculations only. Use getWidth() to see how wide a view is after layout.
Returns
The measured width of this view as a bit mask.
得到的是最近一次調用measure()方法測量後得到的是View的寬度,它應該僅僅用在測量和Layout的計算中。再看源碼:
public final int getMeasuredWidth() {
return mMeasuredWidth & MEASURED_SIZE_MASK;
}
return The raw measured width of this view 獲得的是原始的測量寬度。所以說getMeasuredWidth()是對View上的內容進行測量後得到的View內容占據的寬度。前提是你必須在父布局的onLayout()方法或者此View的onDraw()方法裡調用measure(0,0);(measure中的參數的值你自己可以定義),否則你得到的結果和getWidth()得到的結果是一樣的。
區別
getMeasuredWidth:對View上的內容進行測量後得到的View內容占據的寬度的。
getWidth:View在設定號布局後整個View的寬度。
使用場合
getMeasuredWidth:在自定義view重寫onLayout時、在我們用layoutinflater動態加載view後想獲得view的原始寬度時。
getWidth:一般在view已經布局後呈現出來了,想獲取寬度時。