There is a ViewPager - I want to realize the ability for the user to turn on automatic scrolling, added a button in the bar to click on which should start and then, when pressed again, stop auto-browsing, there is code that performs the first part, but it doesn’t come out with a stop. Please help!

case R.id.menu_auto_slide: if (auto_slide) { auto_slide = false; menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_stop_white_24dp)); final Handler handler = new Handler(); Thread myThread = new Thread( // создаём новый поток new Runnable() { // описываем объект Runnable в конструкторе public void run() { for (int i = pageCurrent; i < pagerAdapter.getCount() - 1; i++) { final int value = i; try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } handler.post(new Runnable() { @Override public void run() { pager.setCurrentItem(value, true); } }); } } } ); myThread.start(); Log.i(LOG_TAG, "start " + myThread); if (myThread != null) { Log.i(LOG_TAG, "myThread != null"); myThread.interrupt(); } } else { auto_slide = true; menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_play_arrow_white_24dp)); } return true; 

    1 answer 1

    You do not need a separate stream here. Just create a runnable in the field:

     private Handler handler = new Handler(); private int pageCurrent; private Runnable autoScroll = new Runnable() { public void run() { pageCurrent++; pager.setCurrentItem(pageCurrent, true); if (pageCurrent < pagerAdapter.getCount() - 1) { handler.postDelayed(this, 1500); } } }; 

    Then, when you need to start, run handler.post(autoScroll) (after changing the start page to pageCurrent if necessary), and stop using handler.removeCallbacks(autoScroll)