使用weight属性为width时,创建具有相同高度和宽度的RelativeLayout

时间:2016-01-24 10:07:33

标签: android android-layout

我有一个RelativeLayout的宽度为weight属性,并使用130dp作为高度,但它看起来像一个矩形,现在我想要高度等于宽度(我希望实现到正方形)风格),如下图所示:

enter image description here

这是我的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>

3 个答案:

答案 0 :(得分:3)

使用自定义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);
    }
}

答案 1 :(得分:2)

自己实施RelativeLayout aspect ratio ImageView

的代码示例

代码示例:

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

[...]

}

答案 2 :(得分:0)

考虑不同的设备屏幕,有一个解决方案:

  1. 获取屏幕宽度。 w ^
  2. 除以W:W / 2
  3. 将RelativeLayout的每个高度设置为W / 2
  4. 我已经使用此解决方案在不同的屏幕上设置具有固定比率的图像。

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