2017-10-17 127 views
0

我在Android中使用scrollView进行了一项活动。 scrollView显示包含多个项目(文本,更多布局,内部等)的固定布局。当活动加载时,我显示布局并开始下载图像 - 下载图像时,通过将它添加到位于主布局开头/顶部的RelativeLayout中,将其显示在scrollView中。如何防止scrollView更新

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

为了解决这个问题,我得到了下载的图像的高度,检查图像是否离开屏幕,如果是这样,我调用scrollView.scrollBy(0, imageHeight);调整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); 
    } 

我需要纠正,这是加载/调整过程之前禁用屏幕更新或滚动视图更新后启用它的方式是什么。

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

+2

程序员更擅长阅读源代码。 ; p – user1506104

+0

添加了显示调整过程的代码 – user501223

回答

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