ListView 拉出回弹效果 overscroll,阻尼效果

来源:互联网 发布:手机网络铃声 编辑:程序博客网 时间:2024/04/30 08:52


一  Android 9 之后才新增的API. 原理是 

     1. 在View中增加了overSrollBy方法,用于记录x, y 轴上滚动的之

     2. 在AbsListView的onTouchEvent中判断是否到达边界(顶部 或 底部) ,然后调用view.overScrollBy ,传入 mScrollY等参数

     3. overScrollBy 最终赋值给View的mScrollX, mScrollY 两个变量

      4. 在AbsListView中调用完overScrollBy之后,调用invalidate重绘


二  下面是一个直接使用API的例子

1. 自定义ListView

public class BounceListView extends ListView{    private static final int MAX_Y_OVERSCROLL_DISTANCE = 200;         private Context mContext;    private int mMaxYOverscrollDistance;         public BounceListView(Context context){        super(context);        mContext = context;        initBounceListView();    }         public BounceListView(Context context, AttributeSet attrs){        super(context, attrs);        mContext = context;        initBounceListView();    }         public BounceListView(Context context, AttributeSet attrs, int defStyle){        super(context, attrs, defStyle);        mContext = context;        initBounceListView();    }         private void initBounceListView(){        //get the density of the screen and do some maths with it on the max overscroll distance        //variable so that you get similar behaviors no matter what the screen size                 final DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();        final float density = metrics.density;                 mMaxYOverscrollDistance = (int) (density * MAX_Y_OVERSCROLL_DISTANCE);    }         @Override    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent){         //This is where the magic happens, we have replaced the incoming maxOverScrollY with our own custom variable mMaxYOverscrollDistance;         return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, mMaxYOverscrollDistance, isTouchEvent);      }     }



2. Activity

public class MainActivity extends Activity {@Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);                LinearLayout linearLayout = new LinearLayout(this);        linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));                setContentView(linearLayout);                        BounceListView bounceListView = new BounceListView(this);                String[] data = new String[30];        for (int i = 0; i < data.length; i++) {data[i] = "天天记录 " + i; }                ArrayAdapter<String> arrayAdapter =         new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, data);                bounceListView.setAdapter(arrayAdapter);                linearLayout.addView(bounceListView);    }    }


资料:

Android Overscroll: Revisited



转载请注明出处:http://blog.csdn.net/love_world_/article/details/8155350



2013-04-08   更新,这种效果也叫“阻尼效果”



原创粉丝点击