Search code examples
androidandroid-widgetandroid-animationandroid-scrollview

Move horizontalscrollView of Android from left to right


I'm using horizontalscrollView along with the animation to move set of images as a slideshow. I'm able to move the images from right to left using the following code :

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

}

I now want to move the images from right to left as a slideshow. I'm unable to find the right formula/logic. Kindly assist me. :(


Solution

  • Before starting the timer, set:

    scrollPos= scrollMax;
    

    Then use this moveScrollView function:

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

    For calculating the width of horizontalScrollview content:

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