一、效果图
image.png二、代码
layout_main.xml
<androidx.viewpager.widget.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingLeft="40dp"
android:paddingTop="24dp"
android:paddingRight="40dp"
android:paddingBottom="20dp"/>
android:clipToPadding此属性表示: 用来定义ViewGroup是否允许在padding中绘制。默认情况下为true,为true的情况下, 那么绘制的区域会把padding部分剪裁。若为false,那么控件的绘制区域包含padding部分
默认情况下,childWidthSize就是页面item的宽度了,等于ViewPager的宽度减去左右Padding。我们给ViewPager设置了左右Padding,页面的宽度就变小了,设置clipToPadding=false,则padding部分可以绘制显示,那么左右的item也就显示出来了。
layout_item_one.xml
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/iv_one"
android:background="#8153BE"/>
layout_item_two.xml
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/iv_two"
android:background="#FF5040"/>
MainActivity.java
private int currentVpPosition = 0;
private ViewPager vp;
private ArrayList<View> viewList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.layout_main);
vp= (ViewPager)findViewById(R.id.vp);
initView();
}
private void initView(){
View viewOne=inflater.inflate(R.layout.layout_item_two, null, false);
View viewTwo=inflater.inflate(R.layout.layout_item_two, null, false);
viewList.add(viewOne);
viewList.add(viewTwo);
ImageView iv_one =viewOne.findViewById(R.id.iv_one);
ImageView iv_two =viewOne.findViewById(R.id.iv_two);
float scale = this.getResources().getDisplayMetrics().density;
int margin=(int) (16 * scale + 0.5f);
//在代码中设置margin为16dp,在xml文件中设置margin无效
vp.setPageMargin(margin);
vp.setAdapter(new MyAdapter());
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
currentVpPosition = position;
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
public class MyAdapter extends PagerAdapter {
@Override
public int getCount() {
return viewList.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view == o;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
container.addView(viewList.get(position));
return viewList.get(position);
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView(viewList.get(position));
}
}
}
网友评论