我有一个imageview。我想让它的宽度为fill_parent。我想让它的高等于宽度。例如:

<ImageView
  android:layout_width="fill_parent"
  android:layout_height="whatever the width ends up being" />

在布局文件中,不需要创建自己的视图类,这样的事情可能吗?

谢谢


当前回答

我确实喜欢这个-

layout.setMinimumHeight(layout.getWidth());

其他回答

也许这能回答你的问题:

<ImageView
    android:id="@+id/cover_image"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true" />

对于这种特定的情况,您可以忽略scaleType属性。

在Android中26.0.0 PercentRelativeLayout已弃用。

解决这个问题的最好方法是使用这样的ConstraintLayout:

<android.support.constraint.ConstraintLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

    <ImageView android:layout_width="match_parent"
               android:layout_height="0dp"
               android:scaleType="centerCrop"
               android:src="@drawable/you_image"                       
               app:layout_constraintDimensionRatio="1:1"/>


</android.support.constraint.ConstraintLayout>

下面是一个关于如何将ConstraintLayout添加到项目中的教程。

我不能让David Chu的答案为RecyclerView项工作,并找出我需要约束ImageView到父。设置ImageView宽度为0dp,并将其开始和结束约束为父对象。我不确定是否设置宽度wrap_content或match_parent在某些情况下工作,但我认为这是一个更好的方式,让一个ConstraintLayout的子填充它的父。

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintDimensionRatio="1:1"/>

</androidx.constraintlayout.widget.ConstraintLayout>

2021年7月28日更新,使用AndroidX而不是支持库

首先,确保你的项目导入了AndroidX,按照下面的说明操作。

然后将你的图像包装在一个ConstraintLayout中,它的字段如下:

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1" />

</androidx.constraintlayout.widget.ConstraintLayout>

在这里看到的

为了将ImageView设置为屏幕的一半,你需要为ImageView添加以下内容:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:scaleType="fitXY"
    android:adjustViewBounds="true"/>

然后将高度设置为宽度,需要在代码中完成。在你的GridView适配器的getView方法中,设置ImageView的高度等于它的测量宽度:

mImageView.getLayoutParams().height = mImageView.getMeasuredWidth();