LayoutParams是ViewGroup的内部类,用于设置和获取View在父容器中的布局参数。
使用LayoutParams的步骤如下:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
params.weight = 1;
view.setLayoutParams(params);
完整的示例代码如下:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
params.weight = 1;
view.setLayoutParams(params);
以上代码将创建一个LinearLayout.LayoutParams对象,并设置宽度为MATCH_PARENT、高度为WRAP_CONTENT、权重为1,然后将这个LayoutParams对象设置给view。