【问题标题】:Why is the color transition animation wrong when ViewPager scroll left?为什么 ViewPager 向左滚动时颜色过渡动画错误?
【发布时间】:2015-02-15 02:28:51
【问题描述】:

我将具有透明背景的 ViewPager 放在另一个背景视图上,当 ViewPager 滚动时,我会通过平滑的颜色过渡来更改背景视图的颜色,例如:

  1. 在第 1 页上,背景为红色。
  2. 当 ViewPager 从第 1 页滚动到第 2 页时,我将背景替换为 LayerDrawable,顶部为红色,底部为蓝色。
  3. 在滚动过程中,我降低了顶层的 Alpha,显示了从 RED 到 BLUE 的过渡。
  4. 最后,在第 2 页,滚动完成后,我将背景更改为蓝色。

当我从左到右滚动时,它按预期工作,但是当我向左滚动时,似乎下层和上层颠倒了。

这是我的代码:

private int[] colors = {Color.BLUE, Color.RED, Color.GREEN, Color.CYAN};
private int currentPage;
private LayerDrawable layersDrawable;
@Override
public void onPageScrollStateChanged(int state) {
    if(state==ViewPager.SCROLL_STATE_DRAGGING){

    }else if(state==ViewPager.SCROLL_STATE_IDLE){
        currentPage = pager.getCurrentItem();
        setBackground(new ColorDrawable(colors[currentPage%4]));
        layersDrawable = null;
    }
}
@Override
public void onPageScrolled(int pos, float positionOffset, int positionPixels) {
    if(positionOffset==0) return;
    if(layersDrawable==null){
        int bottomColor;
        Log.i("POSITION", currentPage+" "+pos);
        if(pos<currentPage){
            //scroll left
            bottomColor = colors[(currentPage+3)%4];
        }else{
            bottomColor = colors[(currentPage+1)%4];
        }
        ColorDrawable bottom = new ColorDrawable(bottomColor);
        ColorDrawable top = new ColorDrawable(colors[currentPage%4]);
        Log.i("COLOR", "TOP:"+colors[currentPage%4]);
        Drawable[] layers = {bottom, top};
        layersDrawable = new LayerDrawable(layers);
        setBackground(layersDrawable);
    }
    ColorDrawable top = (ColorDrawable)layersDrawable.getDrawable(1);
    top.setAlpha((int)(255*(1-positionOffset)));
}

这真的很奇怪......你能弄清楚我做错了什么吗?

【问题讨论】:

    标签: android android-viewpager android-drawable layerdrawable


    【解决方案1】:

    我太傻了,我发现positionOffset实际上是左边显示的页面百分比,所以当向左滚动时,

    top.setAlpha((int)(255*(1-positionOffset)));
    

    应该改为:

    top.setAlpha((int)(255*positionOffset));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2022-01-13
      • 1970-01-01
      • 2011-12-24
      相关资源
      最近更新 更多