本文已参与「新人创作礼」活动,一起开启掘金创作之路。
需求是这样的: 有两种图片需要显示,一种是640640,一种是19201080的图片。 如果是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的大小修改。
public void setImageviewLayout(int width, int height) {
ViewGroup.LayoutParams params = detailCameraPicture.getLayoutParams();
params.width = width;
params.height = height;
detailCameraPicture.setLayoutParams(params);
scrollToMiddle(width);
}
然后图片加载后还需要居中显示,让图片滚动到中间,显示中间的部分,然后能够拖动
public void scrollToMiddle(int childWidth) {
int scrollViewWidth = horizontalScrollView.getWidth();
int offset = (childWidth - scrollViewWidth) / 2 - horizontalScrollView.getScrollX();
if (offset > 0) {
horizontalScrollView.smoothScrollBy(offset, 0);
}
}
但是效果总是不尽人意,当切换到填充屏幕宽度时,高度是正确的,宽度总是保持之前的模式的宽度。开始想着是不是没有重新计算布局啊。 使用如下
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>
运行后一切正常。
如果此时出现了另一个问题,加上HorizontalScrollView后,虽然我已经设了FrameLayout的宽度是fill_parent。但当内容较少时,FrameLayout还是根据内容自适应宽度,不能满屏。
此时,需要设置一个属性就能解决问题了。设置HorizontalScrollView的Android:fillViewport="true"。也就是设置是否将HorizontalScrollView的内容宽度拉伸以适应视口(viewport),这样问题就可以解决了。希望对你有所帮助。
最终的代码如下:
<HorizontalScrollView android:id="@+id/horizontalScrollView" android:layout_width="match_parent" android:layout_height="wrap_content" android:fillViewport="true" 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>