从左到右移动Android的horizo​​ntalscrollView

时间:2012-03-01 10:34:02

标签: android android-widget android-animation android-scrollview

我正在使用 horizo​​ntalscrollView 和动画来将图像组移动为幻灯片。我可以使用以下代码从右向左移动图像:

 public void getScrollMaxAmount(){
    int actualWidth = (horizontalOuterLayout.getMeasuredWidth()-512);
    scrollMax   = actualWidth;
}

public void startAutoScrolling(){
    if (scrollTimer == null) {
        scrollTimer =   new Timer();
        final Runnable Timer_Tick = new Runnable() {
            public void run() {
                moveScrollView();
            }
        };

        if(scrollerSchedule != null){
            scrollerSchedule.cancel();
            scrollerSchedule = null;
        }
        scrollerSchedule = new TimerTask(){
            @Override
            public void run(){
                runOnUiThread(Timer_Tick);
            }
        };

        scrollTimer.schedule(scrollerSchedule, 30, 30);
    }
}

public void moveScrollView(){
    scrollPos   =   (int) (horizontalScrollview.getScrollX() + 1.0);
    if(scrollPos >= scrollMax){
        scrollPos = 0;
    }
    horizontalScrollview.scrollTo(scrollPos, 0);

}

我现在想以幻灯片形式从右到左移动图像。我无法找到合适的公式/逻辑。请帮助我。 :(

1 个答案:

答案 0 :(得分:1)

在启动计时器之前,请设置:

scrollPos= scrollMax;

然后使用此moveScrollView函数:

public void moveScrollView(){
    scrollPos   =   (int) (horizontalScrollview.getScrollX() - 1.0);
    if(scrollPos <= 0){
        scrollPos = scrollMax;
    }
    horizontalScrollview.scrollTo(scrollPos, 0);
}

用于计算horizo​​ntalScrollview内容的宽度:

protected void onCreate(Bundle savedInstanceState) 
{
        ...

    horizontalScrollview= (HorizontalScrollView) findViewById(R.id.hsv);
    ViewTreeObserver vto = horizontalScrollview.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            horizontalScrollview.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            scrollMax= horizontalScrollview.getChildAt(0).getMeasuredWidth()-getWindowManager().getDefaultDisplay().getWidth();

        }
    });     
}