AndroidはViewPagerの無限ループロールバックを実現

13090 ワード


AndroidはViewPagerの無限ループロールバックを実現
Androidシステムが提供するViewPagerの標準方式は左右が自由にスライドできるが、一番左の極限位置にスライドするのが最初のpageで、一番右の位置にスライドするのが最後のpageで、一番左または一番右にスライドすると、スライド/スクロールできなくなり、AndroidシステムのデフォルトのViewPager実装方式である.しかし、開発者は、現在1、2、3、4、5の5つのPageがあるなど、ViewPagerがスマートに無限にスクロールして巻き返すことを望んでいる場合があります.(1)ユーザの指が右から右/一番後ろのページ5まで左にスクロールされたとき、ユーザが引き続きViewPagerを引きずって左にスライドすると、ViewPagerは最初のPage->1に巻き返し、次いで2,3,4,5にループする.(2)逆に、ユーザの指が左から右へ、一番左の最初のPage:1まで滑ったときに、この時点で引き続きViewPagerを引きずって左から右へ滑っていくと、5に回り込み、次いで4,3,2,1となる.このようなViewPagerを「無限ループロールバック」というViewPagerと呼ぶ.このタイプのViewPagerネットワークには多くの実装方法があり、現在はプロセスの広いコード実装が与えられています.テストの作成java:
package zhangphil.demo;

import java.util.Random;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		LoopViewPager viewpager = (LoopViewPager) findViewById(R.id.viewpager);
		viewpager.setAdapter(new SamplePagerAdapter());
	}

	public class SamplePagerAdapter extends PagerAdapter {
		private final Random random = new Random();
		private int mSize;

		public SamplePagerAdapter() {
			mSize = 5;
		}

		public SamplePagerAdapter(int count) {
			mSize = count;
		}

		@Override
		public int getCount() {
			return mSize;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public void destroyItem(ViewGroup view, int position, Object object) {
			view.removeView((View) object);
		}

		@Override
		public Object instantiateItem(ViewGroup view, int position) {
			TextView textView = new TextView(view.getContext());

			textView.setText(position + 1 + "");
			textView.setBackgroundColor(0xff000000 | random.nextInt(0x00ffffff));
			textView.setGravity(Gravity.CENTER);
			textView.setTextColor(Color.WHITE);
			textView.setTextSize(50);
			view.addView(textView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

			return textView;
		}

		//   item
		public void addItem() {
			mSize++;
			notifyDataSetChanged();
		}

		//   item
		public void removeItem() {
			mSize--;
			mSize = mSize < 0 ? 0 : mSize;

			notifyDataSetChanged();
		}
	}
}

MainActivity.JAvaに必要なレイアウトファイルactivity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="zhangphil.demo.MainActivity" >

    <zhangphil.demo.LoopViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

コアキーLoopViewPager.JAvaクラスとLoopViewPager.JAva依存LoopPagerAdapterWrapper.java!
LoopViewPager.java:
package zhangphil.demo;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import java.util.ArrayList;
import java.util.List;

public class LoopViewPager extends ViewPager {
	private static final boolean DEFAULT_BOUNDARY_CASHING = false;
	private static final boolean DEFAULT_BOUNDARY_LOOPING = true;

	private LoopPagerAdapterWrapper mAdapter;
	private boolean mBoundaryCaching = DEFAULT_BOUNDARY_CASHING;
	private boolean mBoundaryLooping = DEFAULT_BOUNDARY_LOOPING;
	private List<OnPageChangeListener> mOnPageChangeListeners;

	/**
	 * helper function which may be used when implementing FragmentPagerAdapter
	 *
	 * @return (position-1)%count
	 */
	public static int toRealPosition(int position, int count) {
		position = position - 1;
		if (position < 0) {
			position += count;
		} else {
			position = position % count;
		}
		return position;
	}

	/**
	 * If set to true, the boundary views (i.e. first and last) will never be
	 * destroyed This may help to prevent "blinking" of some views
	 */
	public void setBoundaryCaching(boolean flag) {
		mBoundaryCaching = flag;
		if (mAdapter != null) {
			mAdapter.setBoundaryCaching(flag);
		}
	}

	public void setBoundaryLooping(boolean flag) {
		mBoundaryLooping = flag;
		if (mAdapter != null) {
			mAdapter.setBoundaryLooping(flag);
		}
	}

	@Override
	public void setAdapter(PagerAdapter adapter) {
		mAdapter = new LoopPagerAdapterWrapper(adapter);
		mAdapter.setBoundaryCaching(mBoundaryCaching);
		mAdapter.setBoundaryLooping(mBoundaryLooping);
		super.setAdapter(mAdapter);
		setCurrentItem(0, false);
	}

	@Override
	public PagerAdapter getAdapter() {
		return mAdapter != null ? mAdapter.getRealAdapter() : mAdapter;
	}

	@Override
	public int getCurrentItem() {
		return mAdapter != null ? mAdapter.toRealPosition(super.getCurrentItem()) : 0;
	}

	public void setCurrentItem(int item, boolean smoothScroll) {
		int realItem = mAdapter.toInnerPosition(item);
		super.setCurrentItem(realItem, smoothScroll);
	}

	@Override
	public void setCurrentItem(int item) {
		if (getCurrentItem() != item) {
			setCurrentItem(item, true);
		}
	}

	@Override
	public void setOnPageChangeListener(OnPageChangeListener listener) {
		addOnPageChangeListener(listener);
	}

	@Override
	public void addOnPageChangeListener(OnPageChangeListener listener) {
		if (mOnPageChangeListeners == null) {
			mOnPageChangeListeners = new ArrayList<>();
		}
		mOnPageChangeListeners.add(listener);
	}

	@Override
	public void removeOnPageChangeListener(OnPageChangeListener listener) {
		if (mOnPageChangeListeners != null) {
			mOnPageChangeListeners.remove(listener);
		}
	}

	@Override
	public void clearOnPageChangeListeners() {
		if (mOnPageChangeListeners != null) {
			mOnPageChangeListeners.clear();
		}
	}

	public LoopViewPager(Context context) {
		super(context);
		init(context);
	}

	public LoopViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	private void init(Context context) {
		if (onPageChangeListener != null) {
			super.removeOnPageChangeListener(onPageChangeListener);
		}
		super.addOnPageChangeListener(onPageChangeListener);
	}

	private OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {
		private float mPreviousOffset = -1;
		private float mPreviousPosition = -1;

		@Override
		public void onPageSelected(int position) {

			int realPosition = mAdapter.toRealPosition(position);
			if (mPreviousPosition != realPosition) {
				mPreviousPosition = realPosition;

				if (mOnPageChangeListeners != null) {
					for (int i = 0; i < mOnPageChangeListeners.size(); i++) {
						OnPageChangeListener listener = mOnPageChangeListeners.get(i);
						if (listener != null) {
							listener.onPageSelected(realPosition);
						}
					}
				}
			}
		}

		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			int realPosition = position;
			if (mAdapter != null) {
				realPosition = mAdapter.toRealPosition(position);

				if (positionOffset == 0 && mPreviousOffset == 0
						&& (position == 0 || position == mAdapter.getCount() - 1)) {
					setCurrentItem(realPosition, false);
				}
			}

			mPreviousOffset = positionOffset;

			if (mOnPageChangeListeners != null) {
				for (int i = 0; i < mOnPageChangeListeners.size(); i++) {
					OnPageChangeListener listener = mOnPageChangeListeners.get(i);
					if (listener != null) {
						if (realPosition != mAdapter.getRealCount() - 1) {
							listener.onPageScrolled(realPosition, positionOffset, positionOffsetPixels);
						} else {
							if (positionOffset > .5) {
								listener.onPageScrolled(0, 0, 0);
							} else {
								listener.onPageScrolled(realPosition, 0, 0);
							}
						}
					}
				}
			}
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			if (mAdapter != null) {
				int position = LoopViewPager.super.getCurrentItem();
				int realPosition = mAdapter.toRealPosition(position);
				if (state == ViewPager.SCROLL_STATE_IDLE && (position == 0 || position == mAdapter.getCount() - 1)) {
					setCurrentItem(realPosition, false);
				}
			}

			if (mOnPageChangeListeners != null) {
				for (int i = 0; i < mOnPageChangeListeners.size(); i++) {
					OnPageChangeListener listener = mOnPageChangeListeners.get(i);
					if (listener != null) {
						listener.onPageScrollStateChanged(state);
					}
				}
			}
		}
	};
}

LoopPagerAdapterWrapper.java:
package zhangphil.demo;

import android.os.Parcelable;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;

public class LoopPagerAdapterWrapper extends PagerAdapter {

	private PagerAdapter mAdapter;

	private SparseArray<ToDestroy> mToDestroy = new SparseArray<>();

	private static final boolean DEFAULT_BOUNDARY_CASHING = true;
	private static final boolean DEFAULT_BOUNDARY_LOOPING = true;

	private boolean mBoundaryCaching = DEFAULT_BOUNDARY_CASHING;
	private boolean mBoundaryLooping = DEFAULT_BOUNDARY_LOOPING;

	void setBoundaryCaching(boolean flag) {
		mBoundaryCaching = flag;
	}

	void setBoundaryLooping(boolean flag) {
		mBoundaryLooping = flag;
	}

	LoopPagerAdapterWrapper(PagerAdapter adapter) {
		this.mAdapter = adapter;
	}

	@Override
	public void notifyDataSetChanged() {
		mToDestroy = new SparseArray<>();
		super.notifyDataSetChanged();
	}

	int toRealPosition(int position) {
		int realPosition = position;
		int realCount = getRealCount();
		if (realCount == 0)
			return 0;
		if (mBoundaryLooping) {
			realPosition = (position - 1) % realCount;
			if (realPosition < 0)
				realPosition += realCount;
		}

		return realPosition;
	}

	public int toInnerPosition(int realPosition) {
		int position = (realPosition + 1);
		return mBoundaryLooping ? position : realPosition;
	}

	private int getRealFirstPosition() {
		return mBoundaryLooping ? 1 : 0;
	}

	private int getRealLastPosition() {
		return getRealFirstPosition() + getRealCount() - 1;
	}

	@Override
	public int getCount() {
		int count = getRealCount();
		return mBoundaryLooping ? count + 2 : count;
	}

	public int getRealCount() {
		return mAdapter.getCount();
	}

	public PagerAdapter getRealAdapter() {
		return mAdapter;
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		int realPosition = (mAdapter instanceof FragmentPagerAdapter || mAdapter instanceof FragmentStatePagerAdapter)
				? position : toRealPosition(position);

		if (mBoundaryCaching) {
			ToDestroy toDestroy = mToDestroy.get(position);
			if (toDestroy != null) {
				mToDestroy.remove(position);
				return toDestroy.object;
			}
		}
		return mAdapter.instantiateItem(container, realPosition);
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		int realFirst = getRealFirstPosition();
		int realLast = getRealLastPosition();
		int realPosition = (mAdapter instanceof FragmentPagerAdapter || mAdapter instanceof FragmentStatePagerAdapter)
				? position : toRealPosition(position);

		if (mBoundaryCaching && (position == realFirst || position == realLast)) {
			mToDestroy.put(position, new ToDestroy(container, realPosition, object));
		} else {
			mAdapter.destroyItem(container, realPosition, object);
		}
	}

	/*
	 * Delegate rest of methods directly to the inner adapter.
	 */

	@Override
	public void finishUpdate(ViewGroup container) {
		mAdapter.finishUpdate(container);
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return mAdapter.isViewFromObject(view, object);
	}

	@Override
	public void restoreState(Parcelable bundle, ClassLoader classLoader) {
		mAdapter.restoreState(bundle, classLoader);
	}

	@Override
	public Parcelable saveState() {
		return mAdapter.saveState();
	}

	@Override
	public void startUpdate(ViewGroup container) {
		mAdapter.startUpdate(container);
	}

	@Override
	public void setPrimaryItem(ViewGroup container, int position, Object object) {
		mAdapter.setPrimaryItem(container, position, object);
	}

	/*
	 * End delegation
	 */

	/**
	 * Container class for caching the boundary views
	 */
	static class ToDestroy {
		ViewGroup container;
		int position;
		Object object;

		public ToDestroy(ViewGroup container, int position, Object object) {
			this.container = container;
			this.position = position;
			this.object = object;
		}
	}
}

読者が興味があれば、上の2つのコアキーコードを自分のプロジェクトコードパッケージに直接入れて、自分が書いたクラスとして直接使えばいいです.レイアウトを書くときはView Pagerを書かないで、私が書いたレイアウトファイルのようにLoopView Pagerを使います.