Search code examples
androidandroid-imageviewandroid-xmlandroid-bitmap

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?


Solution

  • 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);
    }