自定义控件中比如在:自定义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