majid
majid

Reputation: 723

create the RelativeLayout with the same height and width when using the weight property for width

I have a RelativeLayout with the weight property for width , and using the 130dp for height , but it seem's like a rectangle and now i want height equal to width (i want to achieve to square style) , like this image :

enter image description here

this is my xml :

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="130dp"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:background="#00c4ff"
            android:onClick="blockClick">

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="130dp"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:background="#00c4ff"
            android:onClick="blockClick">

        </RelativeLayout>
    </LinearLayout>

Upvotes: 0

Views: 507

Answers (3)

Xin Meng
Xin Meng

Reputation: 2110

Thinking about different screen of device, there is one solution:

  1. Get the width of the screen. W
  2. divide the W: W/2
  3. Set every height of the RelativeLayout with W/2

I have used this solution to set the image View with fix ratio on different screen.

    layout.width = getResources().getDisplayMetrics().widthPixels;
    layout.height = (int) (layout.width / (2.0));
    mRelativeView.setLayoutParams(layout);

Upvotes: 0

dieter_h
dieter_h

Reputation: 2727

Make your own implementation of RelativeLayout Code sample for aspect ratio ImageView

Code example:

public class MyRelativeLayout extends RelativeLayout{

[...]

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

    int newWidth = getMeasuredWidth();
    int newHeight = newWidth;

    setMeasuredDimension(newWidth, newHeight);
  }

[...]

}

Upvotes: 3

Ashutosh Verma
Ashutosh Verma

Reputation: 338

Use custom RelativeLayout...

public class SquareRelativeLayout extends RelativeLayout {

    public SquareRelativeLayout(Context context) {
        super(context);
    }

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

    public SquareRelativeLayout(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();
        setMeasuredDimension(width, width);
    }
}

Upvotes: 3

Related Questions