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

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

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

谢谢


当前回答

对于现在路过的人,在2017年,实现你想要的最好的新方法是使用这样的ConstraintLayout:

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

不要忘记根据你的布局需要在所有四个方向上添加约束。

用ConstraintLayout构建一个响应式UI

此外,到目前为止,PercentRelativeLayout已经被弃用(参见Android文档)。

其他回答

我不能让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>

这可以使用LayoutParams来动态设置视图高度,一旦你在运行时知道了视图宽度。你需要使用一个可运行线程,以便在运行时获得视图的宽度,否则你将试图在你知道视图的宽度之前设置高度,因为布局还没有绘制。

下面是我解决问题的例子:

final FrameLayout mFrame = (FrameLayout) findViewById(R.id.frame_id);

    mFrame.post(new Runnable() {

        @Override
        public void run() {
            RelativeLayout.LayoutParams mParams;
            mParams = (RelativeLayout.LayoutParams) mFrame.getLayoutParams();
            mParams.height = mFrame.getWidth();
            mFrame.setLayoutParams(mParams);
            mFrame.postInvalidate();
        }
    });

LayoutParams必须是你的视图所在的父视图的类型。我的FrameLayout在xml文件中的RelativeLayout中。

    mFrame.postInvalidate();

调用强制视图重绘,而在一个单独的线程比UI线程

如果你的图像视图在一个约束布局中,你可以使用以下约束来创建一个正方形的图像视图,确保使用1:1来制作正方形

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

也许这能回答你的问题:

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

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

对于现在路过的人,在2017年,实现你想要的最好的新方法是使用这样的ConstraintLayout:

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

不要忘记根据你的布局需要在所有四个方向上添加约束。

用ConstraintLayout构建一个响应式UI

此外,到目前为止,PercentRelativeLayout已经被弃用(参见Android文档)。