AlanSTACK
AlanSTACK

Reputation: 6065

Custom SquareView - children not behaving with match_parent || wrap_content

So I needed a view to be always square and I wrote the following custom class

public class SquareView extends LinearLayoutCompat
{
    public SquareView(Context context)
    {
        super(context);
    }

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

    public SquareView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

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

        int width  = getMeasuredWidth();
        int height = getMeasuredHeight();

        if (width > height)
        {
            setMeasuredDimension(width, width);
        }
        else
        {
            setMeasuredDimension(height, height);
        }
    }
}

However, the children of the view that are using match_parent and wrap_content are no longer behaving correctly

How do I fix this?

Upvotes: 1

Views: 30

Answers (1)

Ben P.
Ben P.

Reputation: 54204

This is an answer to your larger problem, not a way to fix your custom view.

ConstraintLayout supports sizing children to have a certain aspect ratio. If you want a square LinearLayout, you can just put it inside a ConstraintLayout and enforce a 1:1 aspect ratio.

https://developer.android.com/training/constraint-layout/index.html#adjust-the-view-size

Set size as a ratio

You can set the view size to a ratio such as 16:9 if at least one of the view dimensions is set to "match constraints" (0dp). To enable the ratio, click Toggle Aspect Ratio Constraint (callout 1 in figure 10), and then enter the width:height ratio in the input that appears.

If both the width and height are set to match constraints, you can click Toggle Aspect Ratio Constraint to select which dimension is based on a ratio of the other. The view inspector indicates which is set as a ratio by connecting the corresponding edges with a solid line.

For example, if you set both sides to "match constraints", click Toggle Aspect Ratio Constraint twice to set the width be a ratio of the height. Now the entire size is dictated by the height of the view (which can be defined in any way) as shown in figure 11.

Upvotes: 2

Related Questions