根据父母调整视图大小

时间:2016-08-20 18:35:15

标签: android android-custom-view

我创建了一个绘制圆圈的自定义视图。它需要xml中的圆圈数。

例如,它在整个屏幕上生成10个圆圈。

<com.dd.view.MyShape
    android:layout_width="match_parent"
    android:layout_height="60dp"
    app:shape_count="10"/>

enter image description here

<LinearLayout
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.dd.view.MyShape
        android:layout_width="100dp"
        android:layout_height="60dp"
        app:shape_count="3"/>
</LinearLayout>

但是当我将此视图放入较小的布局时,圆圈会根据视图的宽度生成。我想根据父视图生成。

我试图覆盖onMeasure方法,但我无法正确。现在看起来像:

enter image description here

这是我的onDraw方法:

 @Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int totalWidth=getMeasuredWidth();
    int major = totalWidth / circleCount;
    int radius = major/2;
    float startPoint = totalWidth / (circleCount * 2);
    for (int i = 0; i < circleCount; i++) {
        if (i % 2 == 0) paint.setColor(Color.GREEN);
        else paint.setColor(Color.BLUE);
        canvas.drawCircle(startPoint + major * i, radius,radius, paint);
    }
}

感谢您的回答。

2 个答案:

答案 0 :(得分:1)

在xml中,对于自定义小部件,使layout_width =“match_parent”而不是在自定义视图java类中实现,它将占用父级的宽度。

<LinearLayout
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.dd.view.MyShape
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:shape_count="3"/>

</LinearLayout>

答案 1 :(得分:0)

您可以通过

获取父布局的宽度
View parent = (View)(this.getParent());
width = parent.getLayoutParams().width

对于在自定义视图上强制父级宽度的解决方案(仅当自定义视图layout_width未提及match_parent / wrap_content时),您需要覆盖onMeasure()。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){

    int width = 0;

    if(getLayoutParams().width == ViewGroup.LayoutParams.MATCH_PARENT){

        width = MeasureSpec.getSize(widthMeasureSpec);

    }else if(getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT){

        width = MeasureSpec.getSize(widthMeasureSpec);

    }else{
        View parent = (View)(this.getParent());

        width = parent.getLayoutParams().width;
    }

    setMeasuredDimension(width,heightMeasureSpec);
}