viewPager motoristic



  • There's a ViewPager-- you want to make it possible for the user to switch off the automatic whistle, the bar has added a press button that should start and then re-pressurize the auto-ling, there's a code that runs the first part, and there's no stopping. 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;
    



  • You don't need a separate flow. Just create 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 have to start. handler.post(autoScroll) (foreseeable change to page Current, if necessary) and stop with help handler.removeCallbacks(autoScroll)




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2