我有一个RelativeLayout
的宽度为weight属性,并使用130dp
作为高度,但它看起来像一个矩形,现在我想要高度等于宽度(我希望实现到正方形)风格),如下图所示:
这是我的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>
答案 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)
考虑不同的设备屏幕,有一个解决方案:
我已经使用此解决方案在不同的屏幕上设置具有固定比率的图像。
layout.width = getResources().getDisplayMetrics().widthPixels;
layout.height = (int) (layout.width / (2.0));
mRelativeView.setLayoutParams(layout);