如何正确调整customview的子项

时间:2017-03-22 10:34:57

标签: android xml android-custom-view

我需要一个视图(称为DayView的自定义视图),它延伸两倍于它所在的scrollView的高度。在此视图中,有两个嵌套视图,其中一个是另一个自定义视图。自定义视图均来自RelativeLayout

布局如下:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"> 

    <!-- Is twice the size as scrollView, see code below -->
    <com.example.DayView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- Should be same size as parent DayView -->
        <include layout="@layout/layout_dayplan_background"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <!-- Should be same size as parent DayView -->
        <com.example.BlockView
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </com.example.DayView>
</ScrollView>

两个嵌套视图(includeBlockView)应与父DayView具有相同的高度。

DayView中,我覆盖了onMeasure,使其大两倍。这有效:(参见倒数第二行的'* 2')

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
    this.setMeasuredDimension(parentWidth, parentHeight);
    this.setLayoutParams(new ScrollView.LayoutParams(parentWidth, parentHeight * 2 ));
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

DayView具有正确的大小,但是,两个嵌套视图不会与父级一起拉伸,但似乎使用wrap_content高度布局规则。

问题

如何让这两个嵌套视图占用与父DayView相同的高度?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法

        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int parentHeight = MeasureSpec.getSize(heightMeasureSpec) * 2;
        this.setMeasuredDimension(parentWidth, parentHeight);
        measureChildren(MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(parentHeight, MeasureSpec.EXACTLY));
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

这里也在测量孩子。也许这可以工作