-3

I have implemented autoscroll for ViewPager. But I called this startAutoScroll() method much earlier, even before the page actually loads or is visible to the user. This results with crash.

I want to start the autoscroll, after all the pages are visible to the user. Please suggest how to handle the notification, when pages are actually visible.

This is my startAutoScroll method.

void startAutoScroll() {
     if (handler == null) {
        new Thread(new Runnable() {
            public void run() {
                handler = new Handler(Looper.getMainLooper()){
                    public void handleMessage(android.os.Message msg) {
                        viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
                    }
                };

                handler.postDelayed(10,10);
            }
        }).start();
    }

    r = new Runnable() {
        public void run() {
            handler.postDelayed(r, 10);

            Message msg = handler.obtainMessage();
            handler.sendMessage(msg);            
        }
    };
}

I got a good solution at How to determine when Fragment becomes visible in ViewPager

Community
  • 1
  • 1
Annada
  • 1,075
  • 1
  • 18
  • 21

1 Answers1

2

I got the answer, by ViewTreeObserver

ViewTreeObserver vto = ViewPager.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new   ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        startAutoScroll();
    ViewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }
});
Annada
  • 1,075
  • 1
  • 18
  • 21