gpt4 book ai didi

Android:垂直 ViewPager

转载 作者:IT老高 更新时间:2023-10-28 13:00:07 27 4
gpt4 key购买 nike

有没有办法制作一个不水平滚动但垂直滚动的ViewPager?!

最佳答案

您可以使用 ViewPager.PageTransformer给人一种垂直 ViewPager 的错觉。要实现垂直滚动而不是水平拖动,您必须覆盖 ViewPager 的默认触摸事件并在处理它们之前交换 MotionEvent 的坐标,例如:

/**
* Uses a combination of a PageTransformer and swapping X & Y coordinates
* of touch events to create the illusion of a vertically scrolling ViewPager.
*
* Requires API 11+
*
*/
public class VerticalViewPager extends ViewPager {

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

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

private void init() {
// The majority of the magic happens here
setPageTransformer(true, new VerticalPageTransformer());
// The easiest way to get rid of the overscroll drawing that happens on the left and right
setOverScrollMode(OVER_SCROLL_NEVER);
}

private class VerticalPageTransformer implements ViewPager.PageTransformer {

@Override
public void transformPage(View view, float position) {

if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);

} else if (position <= 1) { // [-1,1]
view.setAlpha(1);

// Counteract the default slide transition
view.setTranslationX(view.getWidth() * -position);

//set Y position to swipe in from top
float yPosition = position * view.getHeight();
view.setTranslationY(yPosition);

} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}

/**
* Swaps the X and Y coordinates of your touch event.
*/
private MotionEvent swapXY(MotionEvent ev) {
float width = getWidth();
float height = getHeight();

float newX = (ev.getY() / height) * width;
float newY = (ev.getX() / width) * height;

ev.setLocation(newX, newY);

return ev;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev){
boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
swapXY(ev); // return touch coordinates to original reference frame for any child views
return intercepted;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(swapXY(ev));
}

}

当然,您可以根据需要调整这些设置。最终看起来像这样:

VerticalViewPager demo

关于Android:垂直 ViewPager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13477820/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com