安卓:速度型ViewPager滚动(Android: velocity-based ViewPage

2019-06-18 11:56发布

该方式ViewPager卷轴现在的问题是每一个手势项目。 它把扔的姿态以同样的方式无论是全屏一扔快或慢拖动; 末页前进仅一个步骤。

是否有任何可能的项目或会增加基于速度的甩那个滚动基于现有一扔速度的多个项目实例(如果它仍在进行中)并滚动,如果进一步的投掷姿势是广泛和快速?

如果有没有哪里开始像这样的东西?

PS赏金是提供。 与多媒体资料或Horizo​​ntalScrollView引用请没有答案

Answer 1:

这里的技术是扩展ViewPager和模仿的大部分东西寻呼机将在内部做,加之从滚动逻辑Gallery部件。 总的想法是监视一扔(和速度以及所附滚动),然后在作为假拖动事件到底层喂它们ViewPager 。 如果单独做到这一点,就不会工作虽然(你仍然会得到只有一个页面滚动)。 这是因为假拖累的界限,使滚动将有效实现帽。 你可以模仿计算在扩展ViewPager和检测时会出现这种情况,那么只需翻动页面,并继续像往常一样。 使用假拖的好处意味着你不必处理捕捉到的网页或处理的边缘ViewPager

我测试从上的动画演示例如下面的代码,可下载的http://developer.android.com/training/animation/screen-slide.html通过更换ViewPager在ScreenSlideActivity与此VelocityViewPager (无论是在布局activity_screen_slide和场活性之内)。

/*
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 * 
 * Author: Dororo @ StackOverflow
 * An extended ViewPager which implements multiple page flinging.
 * 
 */

package com.example.android.animationsdemo;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.widget.Scroller;

public class VelocityViewPager extends ViewPager implements GestureDetector.OnGestureListener {

private GestureDetector mGestureDetector;
private FlingRunnable mFlingRunnable = new FlingRunnable();
private boolean mScrolling = false;

public VelocityViewPager(Context context) {
    super(context);
}

public VelocityViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    mGestureDetector = new GestureDetector(context, this);
}

// We have to intercept this touch event else fakeDrag functions won't work as it will
// be in a real drag when we want to initialise the fake drag.
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    return true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // give all the events to the gesture detector. I'm returning true here so the viewpager doesn't
    // get any events at all, I'm sure you could adjust this to make that not true.
    mGestureDetector.onTouchEvent(event);
    return true;
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velX, float velY) {
    mFlingRunnable.startUsingVelocity((int)velX);
    return false;
}

private void trackMotion(float distX) {

    // The following mimics the underlying calculations in ViewPager
    float scrollX = getScrollX() - distX;
    final int width = getWidth();
    final int widthWithMargin = width + this.getPageMargin();
    final float leftBound = Math.max(0, (this.getCurrentItem() - 1) * widthWithMargin);
    final float rightBound = Math.min(this.getCurrentItem() + 1, this.getAdapter().getCount() - 1) * widthWithMargin;

    if (scrollX < leftBound) {
        scrollX = leftBound;
        // Now we know that we've hit the bound, flip the page
        if (this.getCurrentItem() > 0) {
            this.setCurrentItem(this.getCurrentItem() - 1, false);
        }
    } 
    else if (scrollX > rightBound) {
        scrollX = rightBound;
        // Now we know that we've hit the bound, flip the page
        if (this.getCurrentItem() < (this.getAdapter().getCount() - 1) ) {
            this.setCurrentItem(this.getCurrentItem() + 1, false);
        }
    }

    // Do the fake dragging
    if (mScrolling) {
        this.fakeDragBy(distX);
    }
    else {
        this.beginFakeDrag();
        this.fakeDragBy(distX);
        mScrolling = true;
    }

}

private void endFlingMotion() {
    mScrolling = false;
    this.endFakeDrag();
}

// The fling runnable which moves the view pager and tracks decay
private class FlingRunnable implements Runnable {
    private Scroller mScroller; // use this to store the points which will be used to create the scroll
    private int mLastFlingX;

    private FlingRunnable() {
        mScroller = new Scroller(getContext());
    }

    public void startUsingVelocity(int initialVel) {
        if (initialVel == 0) {
            // there is no velocity to fling!
            return;
        }

        removeCallbacks(this); // stop pending flings

        int initialX = initialVel < 0 ? Integer.MAX_VALUE : 0;
        mLastFlingX = initialX;
        // setup the scroller to calulate the new x positions based on the initial velocity. Impose no cap on the min/max x values.
        mScroller.fling(initialX, 0, initialVel, 0, 0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE);

        post(this);
    }

    private void endFling() {
        mScroller.forceFinished(true);
        endFlingMotion();
    }

    @Override
    public void run() {

        final Scroller scroller = mScroller;
        boolean animationNotFinished = scroller.computeScrollOffset();
        final int x = scroller.getCurrX();
        int delta = x - mLastFlingX;

        trackMotion(delta); 

        if (animationNotFinished) {
            mLastFlingX = x;
            post(this);
        }
        else {
            endFling();
        }

    }
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distX, float distY) {
    trackMotion(-distX);
    return false;
}

    // Unused Gesture Detector functions below

@Override
public boolean onDown(MotionEvent event) {
    return false;
}

@Override
public void onLongPress(MotionEvent event) {
    // we don't want to do anything on a long press, though you should probably feed this to the page being long-pressed.
}

@Override
public void onShowPress(MotionEvent event) {
    // we don't want to show any visual feedback
}

@Override
public boolean onSingleTapUp(MotionEvent event) {
    // we don't want to snap to the next page on a tap so ignore this
    return false;
}

}

有跟这个有一些小问题,这些问题都会迎刃而解,但我会离开你的,即事情如果你喜欢滚动(拖拉,不丢),你可以最终页面之间的一半(你要捕捉的在ACTION_UP事件)。 此外,触摸事件是为了做到这一点被完全覆盖,所以你将需要相关事件喂到底层ViewPager在适当情况下。



Answer 2:

另一种选择是复制整个ViewPager从支持库实现的源代码和定制determineTargetPage(...)方法。 它负责确定滚动到上扫视姿势的页面。 这种方法是不是超级方便,而且效果很好。 请参见下面的实现代码:

private int determineTargetPage(int curPage, float pageOffset, int velocity, int dx) {
    int target;
    if (Math.abs(dx) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) {
        target = calculateFinalPage(curPage, velocity);
    } else {
        final float truncator = curPage >= mCurItem ? 0.4f : 0.6f;
        target = (int) (curPage + pageOffset + truncator);
    }
    if (mItems.size() > 0) {
        final ItemInfo first = mItems.get(0);
        final ItemInfo last = mItems.get(mItems.size() - 1);

        // Only let the user target pages we have items for
        target = Math.max(first.position, Math.min(target, last.position));
    }
    return target;
}

private int calculateFinalPage(int curPage, int velocity) {
    float distance = Math.abs(velocity) * MAX_SETTLE_DURATION / 1000f;
    float normalDistance = (float) Math.sqrt(distance / 2) * 25;
    int step = (int) - Math.signum(velocity);
    int width = getClientWidth();
    int page = curPage;
    for (int i = curPage; i >= 0 && i < mAdapter.getCount(); i += step) {
        float pageWidth = mAdapter.getPageWidth(i);
        float remainingDistance = normalDistance - pageWidth * width;
        if (remainingDistance >= 0) {
            normalDistance = remainingDistance;
        } else {
            page = i;
            break;
        }
    }
    return page;
}


Answer 3:

我为自己找到了一个更好的实现比在检查答案,这ViewPager表现失色更好,当我想停止滚动https://github.com/Benjamin-Dobell/VelocityViewPager



Answer 4:

ViewPager是支持库类。 下载支持库的源代码和改变约10行代码中的onTouchEvent方法添加所希望的特征。

我利用修改支持库在我的项目大约一年,因为有时我需要修改几行代码来稍作改动或添加新的方法,我不想复制组件的源代码。 我使用的片段和viewpager的修改版本。

但有一个问题,你会得到:一次在约6芒斯你,如果你需要的新功能与新的正式版要合并定制支持库。 并小心的变化,你不想要打破的支持库类的兼容性。



Answer 5:

您可以覆盖滚动型或Horizo​​ntalScrollView类,并添加行为。 有在画廊许多错误,而且我记得它是因为API级别14弃用。



文章来源: Android: velocity-based ViewPager scrolling