How to switch automatically between viewPager pages

后端 未结 8 1309
难免孤独
难免孤独 2020-11-29 08:41

I have an android application that employs a ViewPager with two pages When the activity first displays i would like to present each page in turn to the user so that they kno

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 08:55

    If you want to autoplay viewpager pages but above all solution is correct but after autoplay first item consume delay time but it is wrong after autoplay current item switch quickly. I am adding my code below it is working correctly autoplay/pause.

            @Override
            public void onClick(View v) {
    
                if (!isAutoPlay) {              
                    img_autoplay.setImageResource(R.drawable.pause);
                    int currentcount = getModel().getCurrentIndex();
                    currentcount++;
                    getMainImage().setCurrentItem(currentcount);
                    autoPlay(getMainImage());
                    isAutoPlay = true;
                } else {
                    img_autoplay.setImageResource(R.drawable.auto_play);
                    isAutoPlay = false;
                }
            }
        });
    

    and here is method:

        viewPager.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    if (myAdapter != null
                            && viewPager.getAdapter().getCount() > 0
                            && isAutoPlay) {
                        getWindow().addFlags(
                                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                        int currentcount = getModel().getCurrentIndex();
                        currentcount++;
                        viewPager.setCurrentItem(currentcount);
    
                        if (getModel().isLastCard()) {
                            final Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    isAutoPlay = false;
                                    packFinished();
                                    getWindow()
                                            .clearFlags(
                                                    WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                                }
                            }, 6000);
                        }
                        autoPlay(viewPager);
                    }
                } catch (Exception e) {
    
                }
            }
        }, 6000);
    

提交回复
热议问题