Dynamically set the width and height of the imageview in HorizontalScrollView

Keywords: Android Fragment

The demand is as follows:
There are two kinds of pictures to display, one is 640*640 and the other is 1920*1080.
If it is a 1920 picture, you need to double-click to switch the display mode. By default, the middle part of 1920 is displayed by 640*640, which allows you to swipe left and right to view the entire picture.Double-click and switch to Picture Width to fill the screen width.
The starting layout is as follows:

<HorizontalScrollView
   android:id="@+id/horizontalScrollView"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:overScrollMode="never"
   android:scrollbars="none">

   <ImageView
       android:id="@+id/picture"
       android:layout_width="@dimen/x320"
       android:layout_height="@dimen/x320"
       android:scaleType="fitXY"
       android:src="@drawable/no_image_placeholder"/>

</HorizontalScrollView>

Use the following code to modify the size of the imageview.

ViewGroup.LayoutParams params = picture.getLayoutParams();
params.width = width;
params.height = height;
picture.setLayoutParams(params);

However, the effect is always unsatisfactory. When switching to Fill Screen Width, the height is correct and the width always maintains the width of the previous mode.Start to wonder if the layout hasn't been recalculated.
Use as follows

picture.requestLayout();
picture.forceLayout();

None of them works.Later, it was found that it was actually very simple. To give the imageview a Fragment layout would be OK.The modified layout is as follows.

<HorizontalScrollView
    android:id="@+id/horizontalScrollView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:overScrollMode="never"
    android:scrollbars="none">
    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/picture"
        android:layout_width="@dimen/x320"
        android:layout_height="@dimen/x320"
        android:scaleType="fitXY"
        android:src="@drawable/no_image_placeholder"/>
    </FrameLayout>
</HorizontalScrollView>

Everything works fine after running.

Posted by ranam on Fri, 17 Jul 2020 08:39:10 -0700