Reyjohn
Reyjohn

Reputation: 2734

How to swap the ImageView height and width in xml

I have an ImageView in my xml like this:

<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" />

but the photos I am getting from the server can be in portrait and landscape mode, I just want to swap this height and width when something like this occured. I have tried to convert those dp programaticaly but this doesnt work and the dp got changed. Is there any simple way I am missing?

Upvotes: 0

Views: 253

Answers (2)

bijaykumarpun
bijaykumarpun

Reputation: 707

Since you said image that comes from server can either be portrait or in landscape, here is what you can do to swipe the dimensions programmatically.

Step 1. Determine if the image is landscape or portrait

boolean landscape = false;

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

Step 2. Change height and width accordingly

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

Upvotes: 1

kAvEh
kAvEh

Reputation: 562

use android:adjustViewBounds and maxHeight or minHeight attributes like this:

<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" />

Upvotes: 0

Related Questions