【问题标题】:How to prevent scrollView from updating如何防止滚动视图更新
【发布时间】:2017-10-19 21:46:07
【问题描述】:

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

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

为了解决这个问题,我获取了下载图像的高度,检查图像是否不在屏幕上,如果是,我通过调用 scrollView.scrollBy(0, imageHeight); 调整滚动视图顶部这解决了问题,但它会出现一个短的 '两个动作之间的屏幕闪烁',例如,将图像添加到布局(内容向下移动)和调整滚动视图顶部(内容回到原始位置)。这是“修复”滚动视图位置的代码:

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

我需要纠正的是一种在加载/调整过程之前禁用屏幕更新或滚动视图更新并在之后启用它的方法。

有人知道怎么做吗?

【问题讨论】:

  • 程序员更擅长阅读源代码。 ;p
  • 添加了显示调整过程的代码

标签: android android-scrollview


【解决方案1】:

原来问题是因为对 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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    相关资源
    最近更新 更多