效果:
布局中viewPager必须设置android:clipChildren="false",同时它的父控件也必须设置,且viewpager需要设置与左边及右边的间隔:android:layout_marginLeft、android:layout_marginRight
·布局如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:clipChildren="false"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:clipChildren="false"
android:background="@android:color/white"
android:layout_marginLeft="80dp"
android:layout_marginRight="80dp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
java中
设置缩放及透明效果主要在ScaleTransformer中,其中Viewpager需要设置page的间隔及预加载页数
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ui_pager);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setPageMargin(8);
pager.setOffscreenPageLimit(5);
pager.setPageTransformer(false,new ScaleTransformer());
pager.setAdapter(new MyAdapter(pager));
}
class MyAdapter extends PagerAdapter{
ViewPager mViewPager;
public MyAdapter(ViewPager viewPager){
mViewPager = viewPager;
}
@Override
public int getCount() {
return 5;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(PagerActivity.this);
imageView.setImageResource(R.drawable.a);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mViewPager.setCurrentItem(position);
Toast.makeText(PagerActivity.this,"position:"+position,Toast.LENGTH_SHORT).show();
}
});
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
public class ScaleTransformer extends AlphaTransformer{
private float MIN_ALPHA = 0.5f;
private float MIN_SCALE = 0.70f;
/**
* position取值特点:
* 假设页面从0~1,则:
* 第一个页面position变化为[0,-1]
* 第二个页面position变化为[1,0]
*/
@Override
public void transformPage(View page, float position) {
//缩放效果
if (position < -1 || position > 1) {
page.setAlpha(MIN_ALPHA);
page.setScaleX(MIN_SCALE);
page.setScaleY(MIN_SCALE);
} else if (position <= 1) { // [-1,1]
float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
if (position < 0) {
float scaleX = 1 + 0.3f * position;
page.setScaleX(scaleX);
page.setScaleY(scaleX);
} else {
float scaleX = 1 - 0.3f * position;
page.setScaleX(scaleX);
page.setScaleY(scaleX);
}
page.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA));
}
}
}