Android setLayoutParams的一点注意

639 阅读1分钟

背景:创建自定义视图的高度是一个固定的高度,需要使xml中的定义的高度无效(自定义顶部状态栏); 过程:刚开始,我在构造函数中调用了setLayoutParams方法设定了高度,但是,发现视图加载出来的高度还是xml中定义的高度; 原因:xml解析的过程中,xml解析器会使用解析过程得到的属性值,创建一个新的LayoutParams赋值给创建出来的视图; 解决方案:

  1. 复写setLayoutParams方法,将传入的属性更改掉;
@Override
public void setLayoutParams(ViewGroup.LayoutParams params) {
    if (params != null) {
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = statusBarHeight;
    }
    super.setLayoutParams(params);
}
  1. 复写onMeasure方法,直接修改测量值;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int h = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
    if (h != statusBarHeight) {
        getLayoutParams().height = statusBarHeight;
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                statusBarHeight);
    } else {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}