android listview fling动画太快了

时间:2014-04-21 07:26:29

标签: android listview animation android-listview onfling

我有一个自定义ListView,可以逐页显示项目"#34;。所以我写了OnTouch方法并且它工作得很完美,现在我想写OnFling方法,它将实现我的ListView的平滑和惯性滚动。

问题是smoothScrollToPosition(int position)的滚动动画并不平滑,速度非常快。 smoothScrollToPosition(int position,int offset,int duration)有效,但我的minSdk必须为8,除此之外,尽管有偏移,这个函数仍会严重地放置当前元素。

这是我的OnFling方法的代码:

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) 
{
        if(null == getAdapter()) return false;

        boolean returnValue = false;
        float pty1 = 0, pty2 = 0;

        if (e1 == null || e2 == null)
            return false;

        pty1 = e1.getY();
        pty2 = e2.getY();

        if (pty1 - pty2 > swipeMinDistance && Math.abs(velocityY) > swipeThresholdVelocity) 
        {
            float currentVelocity = Math.min(Math.abs(velocityY), Math.abs(swipeMaxVelocity));

            final int shift = (int) ((currentVelocity / swipeMaxVelocity) * swipeMaxElements + 1);

            if (activeItem < getAdapter().getCount() - shift - 1)
                activeItem = activeItem + shift;
            else
            {
                activeItem = getAdapter().getCount() - 1;
                return false;
            }

            returnValue = true;
        } 
        else if (pty2 - pty1 > swipeMinDistance && Math.abs(velocityY) > swipeThresholdVelocity) 
        {
            float currentVelocity = Math.min(Math.abs(velocityY), Math.abs(swipeMaxVelocity));

            final int shift = (int) ((currentVelocity / swipeMaxVelocity) * swipeMaxElements + 1);

            if (activeItem >= shift)
                activeItem = activeItem - shift;
            else
            {
                activeItem = 0;
                return false;
            }

            returnValue = true;
        }
        smoothScrollToPosition(activeItem);
        return returnValue;
    }

xml内容为:

<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rl_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

 <konteh.example.errortest.CardsListView
     android:id="@+id/cardsListView"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignParentLeft="true"
     android:layout_alignParentTop="true"
     android:smoothScrollbar="true" 
     />

1 个答案:

答案 0 :(得分:0)

解决!我的解决方案是:

    int pixelCount = height * shift * (isForward ? 1 : -1); // calculate approximately shift in pixels
    smoothScrollBy(pixelCount, 2 * DURATION * shift);//this smooth scroll works!
    postDelayed(new Runnable() 
    {
        public void run() 
        {
            smoothScrollBy(0, 0); // Stops the listview from overshooting.
            smoothScrollToPosition(activeItem + 1);
        }
    }, 
    DURATION * shift);

也许它不是最好的解决方案,但它确实有效!

相关问题