0

I'm creating an Android activity where there's a ScrollView with a ViewPager and a TextView in it. The ViewPager's pages are Fragments with a single ImageView in them. I load images with Glide into the ImageView.

I want the image's width to fill the screen and the height to be resized to keep the ratio of the image. The problem is that

<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

with

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

in it won't work. The image's height is always 0.

I found a suboptimal solution: https://stackoverflow.com/a/19505733/4420321. The problem is that I need to know the exact ratio of the image to resize the height properly.

Right now it's working with 800x600 images, but not with any other. Is there any way to get it working with any ratio? Or is there a better solution for this problem?

enter image description here

1 Answers1

0

This would make the image to fill the screen width and height as per the aspect ratio of the original image. To use this method you need to hardcode the aspect ratio.

Display display = getWindowManager().getDefaultDisplay();
ImageView imageView = (LinearLayout) findViewById(R.id.imageView);
int width = display.getWidth(); 
int height = (int) width * 0.75; // 0.75 if image aspect ration is 4:3, change accordingly 
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, height);

I think this will solve your problem.

Akshay Katariya
  • 1,464
  • 9
  • 20
  • Thanks for your answer but this is exactly my current solution. I need to harcdcode the aspect ratio but what if i dont know it or there's multiple images with different ratios? For example i have an image set of 3 800x600 images and another one of 3 1920x1080. – hashtagslam Sep 06 '17 at 11:44