private final void setLayoutParams(View view) {
ViewGroup.LayoutParams linearParams = view.getLayoutParams();
Rect rc = getFramingRect();
linearParams.height = rc.height();
linearParams.width = rc.width();
view.setLayoutParams(linearParams);
}
private final void setLayoutParams(View view) {
// view的parent为RelativeLayout
RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
Rect rc = getFramingRect();
linearParams.height = rc.height();
linearParams.width = rc.width();
linearParams.bottomMargin = rc.top;
view.setLayoutParams(linearParams);
}
Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged. 说明这里设置的参数是提供给parent的。也就是说这个setLayoutParams()是给其父控件看的,其实这也好理解:只有父类可以改变子View的位置布局.而不是说子View可以随意按照自己的想法摆放自己的位置,而不受父控件控制
关于setLayoutParams报错 有两个可能的原因
1.内部view没有用其parent的LayoutParams
在继承BaseAdapter的时候,用getView返回View的时候,用代码控制布局,需要用到View.setLayoutParams,但是报错了,报的是类型转换错误,经过研究,发现,这里不能使用ViewGroup.LayoutParams而必须使用对应父View的LayoutParams类型。如:某View被LinearLayout包含,则该View的setLayoutParams参数类型必须是LinearLayout.LayoutParams。原因在于LinearLayout(或其他继承自ViewGroup的layout,如:RelativeLayout)在进行递归布局的时候,LinearLayout会获取子View的LayoutParams,并强制转换成LinearLayout.LayoutParams.
2.最外层的,不能setLayoutParams 因为它没有parent