如何防止scrollView更新

时间:2017-10-17 06:24:31

标签: android android-scrollview

我在Android中有一个带有scrollView的活动。 scrollView显示具有多个项目(文本,更多布局,iamges等)的固定布局。加载活动时,我显示布局并开始下载图像 - 下载图像时,我将其显示在scrollView中,方法是将其添加到位于主布局开头/顶部的RelativeLayout中。

相对布局的高度设置为WRAP_CONTENT,因此在显示图像之前,其高度为零;当图像添加到图像时,它会调整到图像的高度。问题是,如果用户在加载图像之前向下滚动并且图像的RelativeLayout不在屏幕上,则scrollView的顶部Y会发生变化,内容会向下移动(这会导致看到内容的人分心)。

为了解决这个问题,我得到了下载图像的高度,检查图像是否在屏幕外,如果是,我通过调用scrollView.scrollBy(0, imageHeight);来调整scrollView顶部这样可以解决问题,但它会出现问题在两个动作之间短暂“闪烁”屏幕,例如,将图像添加到布局(内容向下移动)和调整scrollView顶部(内容返回到原始位置)。以下是“修复”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);
    }

我需要纠正这个问题,这是一种在加载/调整过程之前禁用屏幕更新或scrollView更新的方法,并在之后启用它。

任何人都知道如何做到这一点?

1 个答案:

答案 0 :(得分:0)

事实证明问题是因为从一个线程调用了scrollView.scrollBy。删除它解决了这个问题。这是正确的代码:

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();

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, imgHeight);
        parent.setLayoutParams(params);

        if (layoutTop < scrollY)
            scrollview.scrollBy(0, imgHeight);

        img.setVisibility(View.VISIBLE);
    }
相关问题