2013-06-13 62 views

回答

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" /> 

AutoSwitcherViewPager类包

+0

更换<packagename这是否帮助? – Triode

+0

是如果用户手动滑动屏幕,在任何情况下在特定时间之后切换片段。如果用户不手动滑动片段,我想切换。 – user2064024

+0

查看编辑答案... – Triode

相关问题