如何在 xml 中交换 ImageView 的高度和宽度

How to swap the ImageView height and width in xml

我的 xml 中有一个 ImageView,如下所示:

<ImageView
    android:id="@+id/ivMessage"
    android:layout_width="@dimen/two_hundred_dp"
    android:layout_height="@dimen/one_sixty_dp"
    android:layout_alignParentRight="true"
    android:layout_margin="@dimen/ten_dp"
    android:background="@drawable/rounded_rectangle_white"
    android:scaleType="fitXY"
    android:padding="@dimen/ten_dp"
    tools:src="@drawable/logo" />

但是我从服务器获取的照片可以是纵向和横向模式,我只是想在发生这种情况时交换这个高度和宽度。我曾尝试以编程方式转换这些 dp,但这不起作用,dp 已更改。有没有我想念的简单方法?

像这样使用 android:adjustViewBounds 和 maxHeight 或 minHeight 属性:

<ImageView
                android:id="@+id/ivMessage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:maxWidth="@dimen/two_hundred_dp"
                android:maxHeight="@dimen/one_sixty_dp"
                android:adjustViewBounds="true"
                android:layout_margin="@dimen/ten_dp"
                android:background="@drawable/rounded_rectangle_white"
                android:scaleType="fitXY"
                android:padding="@dimen/ten_dp"
                tools:src="@drawable/logo" />

既然你说来自服务器的图像可以是纵向的也可以是横向的,那么你可以通过编程方式滑动尺寸。

步骤 1. 确定图像是横向还是纵向

boolean landscape = false;

if(image.getHeight()>image.getWidth()){
//image is in portrait
landscape = false;
}else{
//image is in landscape
landscape = true;
}

步骤 2. 相应地更改高度和宽度

if(landscape){
imageView.setWidth(200);
imageView.setHeight(160);
}
else{
imageView.setWidth(160);
imageView.setHeight(200);
}