【Android】getwidth和getmeasuredwidth的區別以及兩者的使用情境,androidgetwidth
首先,看getWidth()的官方說明:
public final int getWidth ()Added in API level 1
Return the width of the your view.
Returns
- The width of your view, in pixels.
返回view的寬度,說的不詳細,再看getWidth源碼:
<span style="font-size:18px;"> /** * Return the width of the your view. * * @return The width of your view, in pixels. */ @ViewDebug.ExportedProperty(category = "layout") public final int getWidth() { return mRight - mLeft; }</span>
從源碼可以看出,getwidth返回的是右邊座標減輕座標減去左邊座標,這要在布局之後才能確定它們的座標,也就是說在布局後才能調用getwidth來擷取。所以
getWidth()獲得的寬度是View在設定好布局後整個View的寬度。
而對於getmeasuredwidth,
public final int getMeasuredWidthAndState ()Added in API level 11
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的計算中。再看源碼:
/** * Like {@link #getMeasuredWidthAndState()}, but only returns the * raw width component (that is the result is masked by * {@link #MEASURED_SIZE_MASK}). * * @return The raw measured width of this view. */ 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重寫onLayout時、在我們用layoutinflater動態載入view後想獲得view的原始寬度時。
getWidth:一般在view已經布局後呈現出來了,想擷取寬度時
android view getMeasuredHeight為O
只有在一個控制項的 onMeasure()方法被執行過後,才能使用getMeasuredWidth()取得正確的值,
child.measure(childWidthSpec, childHeightSpec); 這個方法裡面會調用onMeasure()。
android手機布局,這個篩選布局該怎設定控制項?新手講解
用兩個Radio把前面圈圈去掉就行了嘛。