Reputation: 531
i m using view pager to slide the fragments by finger using viewpager in android. its working fine but now i want to do that if user does not touch the screen it automatically changes the fragment to next after every few seconds. kindly help me how to do that.
Upvotes: 1
Views: 2272
Reputation: 11357
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);
}
}
Use this class as your ViewPager
<packagename.AutoSwitcherViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Replace the <packagename
with your AutoSwitcherViewPager
class package
Upvotes: 7