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

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

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

谢谢


当前回答

ImageView "scaleType"函数可以帮助你。

这段代码将保持图像的纵横比和位置在顶部:

android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitStart"

这里有一个很棒的帖子展示了使用scaleType的可能性和外观。

ImageView scaleType样本

其他回答

下面是我解决这个问题的方法:

int pHeight =  picture.getHeight();
int pWidth = picture.getWidth();
int vWidth = preview.getWidth();
preview.getLayoutParams().height = (int)(vWidth*((double)pHeight/pWidth));

preview - imageView,宽度设置为“match_parent”,scaleType设置为“cropCenter”

在imageView src中设置的位图对象。

这对我来说很有效。

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
    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文档)。

我确实喜欢这个-

layout.setMinimumHeight(layout.getWidth());