user3792834
user3792834

Reputation: 135

Resize View According to Parent

I created a custom view which is drawing circles. It takes numbers of circle from xml.

For example its generates 10 circle on whole screen.

<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>

But when I put this view into the smaller layout, circle generates according view's width. I want to generate according to parent view.

I tried to override onMeasure method but I couldn’t correctly. Now It looks like :

enter image description here

And here my onDraw method :

 @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);
    }
}

Thanks for your answers.

Upvotes: 1

Views: 720

Answers (2)

Annada
Annada

Reputation: 1085

You can get parent layout's width by,

View parent = (View)(this.getParent());
width = parent.getLayoutParams().width

For the solution of imposing parent's width(only when custom view layout_width is NOT mentioned match_parent/wrap_content) on custom view, you need to Override 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);
}

Upvotes: 0

Annada
Annada

Reputation: 1085

In the xml, for the custom widget, make the layout_width="match_parent" rather than achieving in custom view java class, it will take parent's width.

<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>

Upvotes: 1

Related Questions