我在Android上有一个活动,带有滚动视图。scrollView显示一个固定布局,其中包含多个项目(文本、更多布局、尺寸等)。加载活动时,我显示布局并开始下载图像-下载图像时,我通过将其添加到主布局开始/顶部的相对布局中,将其显示在滚动视图中。
相对布局的高度设置为WRAP_CONTENT,因此在显示图像之前,其高度为零;当图像添加到其中时,它会调整到图像的高度。问题是,如果用户在加载图像之前向下滚动,并且图像的RelativeLayout不在屏幕上,则scrollView的顶部Y会发生变化,内容会向下移动(这会导致观看内容的人分心)。
为了解决这个问题,我获取下载的图像的高度,检查图像是否在屏幕上,如果是,我通过调用
scrollView.scrollBy(0, imageHeight);
这可以纠正问题,但会在两个操作之间出现短暂的屏幕“闪烁”,例如,将图像添加到布局(内容向下移动)和调整scrollView顶部(内容返回原始位置)。以下是“修复”滚动视图位置的代码:
public void imageLoaded(final ImageView img) {
img.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final int imgHeight = img.getMeasuredHeight();
// image is loaded inside a relative layout - get the top
final RelativeLayout parent = (RelativeLayout) img.getParent();
final int layoutTop = parent.getTop();
// adjust the layout height to show the image
// 1. this changes the scrollview position and causes a first 'flickering'
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, imgHeight);
parent.setLayoutParams(params);
// adjust scrollbar so that the current content position does not change
// 2. this corrects the scrollview position but causes a second 'flickering'
// scrollY holds the scrollView y position (set in the scrollview listener)
if (layoutTop < scrollY)
scrollview.post(new Runnable() {
public void run() {
scrollview.scrollBy(0, imgHeight);
}
});
img.setVisibility(View.VISIBLE);
}
我需要纠正的是,在加载/调整过程之前禁用屏幕更新或滚动视图更新,然后在加载/调整过程之后启用。