自定義控件中比如在:自定義ListView, 流式佈局等 的時候需要測量佈局的寬高
所以這裏講講佈局寬高的測量
下面是MeasureSpec類的測量模式:
MeasureSpec類的測量模式 |
視圖寬、高的賦值方式 |
說明 |
AT_MOST |
MATCH_PARENT |
達到最大 |
UNSPECIFIED |
WRAP_CONTENT |
未指定(實際就是自適應) |
EXACTLY |
具體的dp值 |
精確尺寸 |
下面寫一個例子:
來測試一下上面的理論
效果圖:
activity_main2.xml 中寫要測量佈局 ll_header
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<!--頭佈局-->
<LinearLayout
android:id="@+id/ll_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeee"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="15dp"
android:paddingTop="15dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon_header" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="輕輕下拉,刷新精彩..."
android:textColor="@color/black"
android:textSize="17sp"
android:layout_margin="20dp"
/>
</LinearLayout>
<TextView
android:id="@+id/tv_height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:gravity="left"
android:textColor="@color/black"
android:textSize="17sp"
android:text="頭部的高度是:"
/>
</LinearLayout>
Main2Activity 中調 getRealHeight() 測量高度
/**
* 佈局尺寸的測量
*/
public class Main2Activity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// 初始化控件
LinearLayout ll_header = findViewById(R.id.ll_header);
TextView tv_height = findViewById(R.id.tv_height);
// 計算獲取線性佈局的實際高度
float height = MeasureUtil.getRealHeight(ll_header);
// 顯示頭部高度
tv_height.setText("頭部的高度:"+height);
}
}
MeasureUtil 類中 真正測量的方法 getRealHeight()
佈局 ll_header 高度是測量,所以用的是 MeasureSpec 類的 UNSPECIFIED 模式
// 計算指定線性佈局的實際高度
public static float getRealHeight(View child) {
LinearLayout llayout = (LinearLayout) child;
// 獲得線性佈局的佈局參數
ViewGroup.LayoutParams params = llayout.getLayoutParams();
if (params == null) {
params = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
// 獲得佈局參數裏面的寬度規格
int widthSpec = ViewGroup.getChildMeasureSpec(0, 0, params.width);
int heightSpec;
if (params.height > 0) { // 高度大於0,說明這是明確的dp數值
// 按照精確數值的情況計算高度規格
heightSpec = View.MeasureSpec.makeMeasureSpec(params.height, View.MeasureSpec.EXACTLY);
} else { // MATCH_PARENT=-1,WRAP_CONTENT=-2,所以二者都進入該分支
// 按照不確定的情況計算高度規則
heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
// 重新進行線性佈局的寬高丈量
llayout.measure(widthSpec, heightSpec);
// 獲得並返回線性佈局丈量之後的高度數值。調用getMeasuredWidth方法可獲得寬度數值
return llayout.getMeasuredHeight();
}
源碼下載:
TestCustom ---- app2
https://download.csdn.net/download/zhaihaohao1/11224806