Skip to content
Search

Android.support.v4.view.ViewPager

lastmod 2018-08-17created 2016-06-302 edits

View refresh

A summary of the sequence for a ViewPager View Refresh.

  1. notifyDataSetChanged() on a PagerAdapter only tells the ViewPager that the DataSet has changed. The ViewPager registers and removes Views through getItemPosition(Object) and getCount().
  2. When notifyDataSetChanged() is called, the ViewPager finds out the Position of each Child View by calling getItemPosition(Object). If the Child View returns POSITION_NONE, the ViewPager knows the View has been removed. It then calls destroyItem(ViewGroup, int, Object) to remove the View.

If the ViewPager does not update its Views, you can force an Update as follows.

  1. Override getItemPosition(Object) of the PagerAdapter and return POSITION_NONE from it. This value is -2; with it, the ViewPager redraws every View each time notifyDataSetChanged() is called. It is less efficient, but it solves the problem anyway. Not a recommended approach.
  2. Set a Tag on the Fragment with setTag(), override instantiateItem(View, position) of the PagerAdapter, and recreate only the needed Views based on the Tag value. With this approach, you should not call notifyDataSetChanged() and should attempt the Update through ViewPager.findViewWithTag(Object) instead.

Disable viewpager

To Enable/Disable Paging on a ViewPager, subclass the ViewPager class and override onTouchEvent() and onInterceptTouchEvent() as shown below.

public class CustomViewPager extends ViewPager {
    private boolean isPagingEnabled;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.isPagingEnabled = true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.isPagingEnabled) {
            return super.onTouchEvent(event);
        }
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.isPagingEnabled) {
            return super.onInterceptTouchEvent(event);
        }
        return false;
    }

    public void setPagingEnabled(boolean b) {
        this.isPagingEnabled = b;
    }
}

See also

  • android.support.v4.view.PagerAdapter

Favorite site

References


  1. Android_multiple_view-viewpager_options.pdf ↩