动态设置HorizontalScrollView中imageview的宽度和高度

需求是这样的:
有两种图片需要显示,一种是640*640,一种是1920*1080的图片。
如果是1920的图片则需要双击切换显示模式,默认按640*640显示1920的中间部分,可以左右滑动查看整个图片。双击后切换到图片宽度填充屏幕宽度。
开始布局是这么写的:

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

使用如下代码进行imageview的大小修改。

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

但是效果总是不尽人意,当切换到填充屏幕宽度时,高度是正确的,宽度总是保持之前的模式的宽度。开始想着是不是没有重新计算布局啊。
使用如下

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

都不起作用。后来发现其实很简单,给imageview套一层Fragment布局就OK了。修改后的布局如下。

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

运行后一切正常。

猜你喜欢

转载自blog.csdn.net/ocean20/article/details/78711255