ViewPager已经有了滑动的功能
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.lemon.viewpagerdemo.MainActivity"> <android.support.v4.view.ViewPager android:id="@+id/main_viewpager" android:layout_width="wrap_content" android:layout_height="wrap_content"> </android.support.v4.view.ViewPager> </LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity { private ViewPager mViewPager; private int[] mImgIds = new int[] { R.drawable.a, R.drawable.b, R.drawable.c}; private List<ImageView> mImageViews = new ArrayList<ImageView>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); mViewPager = (ViewPager) findViewById(R.id.main_viewpager); mViewPager.setAdapter(new PagerAdapter(){ @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(mImageViews.get(position)); return mImageViews.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mImageViews.get(position)); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public int getCount() { return mImgIds.length; } });
//setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer)
//用于设置ViewPager切换时的动画效果 mViewPager.setPageTransformer(true,new DepthPageTransformer()); } private void initData() { for (int imgId : mImgIds) { ImageView imageView = new ImageView(getApplicationContext()); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(imgId); mImageViews.add(imageView); } } }
DepthPageTransformer.java
public class DepthPageTransformer implements ViewPager.PageTransformer{ private static final float MIN_SCALE = 0.75f; @Override public void transformPage(View view, float position) { int pageWidth = view.getWidth(); if(position<-1){ // [-Infinity,-1) view.setAlpha(0); }else if(position<=0){// [-1,0] view.setAlpha(1); view.setTranslationX(0); view.setScaleX(1); view.setScaleY(1); }else if(position<=1){// (0,1] view.setAlpha(1-position); view.setTranslationX(pageWidth*-position); float scaleFactor = MIN_SCALE+(1-MIN_SCALE)*(1-Math.abs(position)); view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); }else{//(1,+Infinity] view.setAlpha(0); } } }