view里面存在变更高度的时候,有几种方法:
1、
LayoutParams params = view.getLayoutParams();// 注意得到相应的布局参数
params.height = 300;
view.setLayoutParams(params);
这种方法的弊端是在UI界面并不能即使刷新,这个时候,可以使用
view.post(new Runnable() {
@Override
public void run() {
LayoutParams params = view.getLayoutParams();// 注意得到相应的布局参数
params.height = 300;
view.setLayoutParams(params);
}
});
这个可以及时刷新UI界面view的高度,但是有时候,debug发现,这个方法会无限执行,具体应该是在调用完方法后,会调用requestLayout()
某些方法会触发view.post()
从而导致无限循环。具体情况具体对待。
2
这种方法跟上面的类似,只是新建了一个params参数
// 创建相应的布局参数,然后设置上去
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width,height);
view.setLayoutParams(layoutParams);
这个的弊端就是有可能会改变你布局,你必须要做出相应的设置,必要的时候也可以加上view.post()
这个方法,弊端如上。
3
就是自定义控件,在onMeasure方法中,改变控件高度。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (getChildCount() ==0){
throw new NullPointerException("there is no child in the MaxHeightRelativeLayout");
}
View childAt = getChildAt(0);
if (childAt instanceof EditText) {
MAX_HEIGHT = childAt.getMeasuredHeight() + 32;
} else {
throw new ClassCastException("the first child must be EditView");
}
//============================这里开始==================================
if (heightMode == MeasureSpec.EXACTLY) {
heightSize = heightSize <= MAX_HEIGHT ? heightSize
: (int) MAX_HEIGHT;
}
if (heightMode == MeasureSpec.UNSPECIFIED) {
heightSize = heightSize <= MAX_HEIGHT ? heightSize
: (int) MAX_HEIGHT;
}
if (heightMode == MeasureSpec.AT_MOST) {
heightSize = heightSize <= MAX_HEIGHT ? heightSize
: (int) MAX_HEIGHT;
}
int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize,
heightMode);
super.onMeasure(widthMeasureSpec, maxHeightMeasureSpec);
}