android:更改高度以匹配宽度

Zac*_*ite 0 xml android shapes

非常简短:我已经绘制了3个形状,xml跨越设备的整个宽度:

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/menu_ebook"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:layout_weight="1"
        android:background="@color/menuBlue"
        android:clickable="true"
        android:contentDescription="@string/menu_ebook"
        android:soundEffectsEnabled="false" />

    <ImageView
        android:id="@+id/menu_library"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:layout_marginLeft="1dp"
        android:layout_marginRight="1dp"
        android:layout_weight="1"
        android:background="@color/menuBlue"
        android:clickable="true"
        android:contentDescription="@string/menu_ebook"
        android:soundEffectsEnabled="false" />

    <ImageView
        android:id="@+id/menu_faq"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:layout_weight="1"
        android:background="@color/menuBlue"
        android:clickable="true"
        android:contentDescription="@string/menu_ebook"
        android:soundEffectsEnabled="false" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

这三种形状应始终在每个设备上都是正方形.这是否可以通过xml,如果不是如何以编程方式执行此操作?

澄清:所有3个ImageView的高度应该等于1 ImageView的宽度.

Thx提前

Leo*_*dos 7

你不能轻易做到ImageViews广场.唯一的标准方法是设置exact width = height = some_value.如果在某些时候您知道方形边长,则可以将此值应用于imageViews.

如果你真的想让一些视图成为正方形,你应该创建自定义视图并覆盖onMeasure方法.您可以运行标准测量功能,然后使用setMeasuredDimension设置相等的维度.

例如,如果它是一个ViewGroup:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // simple implementation, this can be done better )
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int squareSize = getMeasuredWidth(); // square size
    int measureSpec = MeasureSpec.makeMeasureSpec(squareSize, MeasureSpec.EXACTLY);
    super.onMeasure(measureSpec, measureSpec); // we should remeasure childrens to fit square
}
Run Code Online (Sandbox Code Playgroud)

或者喜欢这个,如果它的观点:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int squareSize = getMeasuredWidth();
    setMeasuredDimension(squareSize, squareSize);
}
Run Code Online (Sandbox Code Playgroud)

全部覆盖使用视图的宽度作为方形大小.