Android 竖向/纵向滑动ViewPager

VerticalViewPager

public class VerticalViewPager extends ViewPager {

    public VerticalViewPager(@NonNull Context context) {
        super(context);
    }

    public VerticalViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return super.onTouchEvent(swapTouchEvent(MotionEvent.obtain(ev)));
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(swapTouchEvent(MotionEvent.obtain(ev)));
    }

    private MotionEvent swapTouchEvent(MotionEvent event) {
        float width = getWidth();
        float height = getHeight();
        event.setLocation((event.getY() / height) * width, ((event.getX() / width) * height));
        return event;
    }

}
VerticalPageTransformer
public class VerticalPageTransformer  implements ViewPager.PageTransformer {

    @Override
    public void transformPage(View view, float position) {
        if (position >= -1 && position <= 1) {
            view.setTranslationX(view.getWidth() * -position);
            float yPosition = position * view.getHeight();
            view.setTranslationY(yPosition);
        }
    }

}

ViewPagerAdapter

public class ViewPagerAdapter extends PagerAdapter {

    private Context mContext;

    private ArrayList mData = new ArrayList<>();

    BannerPagerAdapter(Context context) {
        this.mContext = context;
    }

    void setData(ArrayList list){
        mData.clear();
        mData.addAll(list);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        return POSITION_NONE;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = View.inflate(mContext,R.layout.viewpager_item,null);
        TextView tv = view.findViewById(R.id.tv);
        tv.setText(mData.get(position));
        container.addView(view);
        return view;
    }

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

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

}

调用

VerticalViewPager viewPager = findViewById(R.id.vertical_viewpager);
BannerPagerAdapter bannerPagerAdapter = new BannerPagerAdapter(this);
viewPager.setPageTransformer(false,new VerticalPageTransformer());
viewPager.setAdapter(bannerPagerAdapter);
ArrayList list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
bannerPagerAdapter.setData(list);

xml文件中最好加一句:

android:overScrollMode="never"

不然会有横向滑动时候出现的滑动边界提示,跟竖向滑动看起来格格不入。

你可能感兴趣的:(Android)