首页 > 解决方案 > 如何在自身内部设置自定义视图高度的一半宽度?

问题描述

android如何LinearLayout在自己内部设置自定义高度的一半。

 @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec / 2);
}

我使用此代码,但孩子的代码被切断了。

标签: androidheightwidthandroid-linearlayout

解决方案


public class CustomLinearLayout extends LinearLayout {

    private static final float RATIO = 0.5f;

    public CustomLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        int customHeight = MeasureSpec.makeMeasureSpec(
                            (int)(MeasureSpec.getSize(widthSpec) * RATIO), MeasureSpec.EXACTLY);
        super.onMeasure(widthSpec, customHeight);
    }
}

推荐阅读