1

我使用视图寻呼机在 android 中使用 viewpager 用手指滑动片段。它工作正常,但现在我想这样做,如果用户不触摸屏幕,它会在每隔几秒后自动将片段更改为下一个。请帮助我如何做到这一点。

4

1 回答 1

7
public class AutoSwitcherViewPager extends ViewPager {



    private Runnable  mSwither = new Runnable() {

        /*
         * (non-Javadoc)
         * @see java.lang.Runnable#run()
         * @since Jun 13, 2013
         * @author rajeshcp
         */
        @Override
        public void run() {
            if( AutoSwitcherViewPager.this.getAdapter() != null )
            {
                int count = AutoSwitcherViewPager.this.getCurrentItem();

                if( count ==  (AutoSwitcherViewPager.this.getAdapter().getCount() - 1) )
                {
                    count = 0;
                }else
                {
                    count++;
                }

                Log.d(this.getClass().getName(), "Curent Page  " + count + "");
                AutoSwitcherViewPager.this.setCurrentItem(count, true);
            }
            AutoSwitcherViewPager.this.postDelayed(this, 5000);
        }
    };


    /**
     * @param context  
     * @return of type AutoSwitcherViewPager
     * Constructor function
     * @since Jun 13, 2013 
     * @author rajeshcp
     */
    public AutoSwitcherViewPager(Context context) {
        this(context, null);
    }

    /**
     * @param context
     * @param attrs  
     * @return of type AutoSwitcherViewPager
     * Constructor function
     * @since Jun 13, 2013 
     * @author rajeshcp
     */
    public AutoSwitcherViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        postDelayed(mSwither, 5000);
    }

    /*
     * (non-Javadoc)
     * @see android.support.v4.view.ViewPager#onTouchEvent(android.view.MotionEvent)
     * @since Jun 13, 2013
     * @author rajeshcp
     */
    @Override
    public boolean onTouchEvent(MotionEvent arg0) {
        switch (arg0.getAction()) {
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP :
            postDelayed(mSwither, 5000);
            break;

        default:
            removeCallbacks(mSwither);
            break;
        }
        return super.onTouchEvent(arg0);
    }



}

使用这个类作为你的ViewPager

<packagename.AutoSwitcherViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<packagename用你的AutoSwitcherViewPager类包替换

于 2013-06-13T05:52:58.297 回答