scrollview 实现滑动到底部再滑动加载数据的功能

来源:互联网 发布:java实战1200例 1 编辑:程序博客网 时间:2024/05/22 04:28

思路:在滑动基础上添加scrollview到底检测事件

1.首先检测是否滑动


// 滑动加载scrollView.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubswitch (event.getAction()) {case MotionEvent.ACTION_DOWN :break;case MotionEvent.ACTION_MOVE ://检查滑动事件 Log.d(TAG,"滑到底部");break;default :break;}}});

2.对scrollview添加到底检测监听事件

但是scrollview 不能像listview那样添加onscrolllistener监听,所以需要自己检测


if (view.getMeasuredHeight() <= v.getScrollY() + v.getHeight()) {        //到底部        Log.d(TAG,"滑到底部");}


3.组合代码


// 滑动加载scrollView.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubswitch (event.getAction()) {case MotionEvent.ACTION_DOWN :break;case MotionEvent.ACTION_MOVE :View view = ((ScrollView) v).getChildAt(0);if (view.getMeasuredHeight() <= v.getScrollY() + v.getHeight()) {//加载数据代码}break;default :break;}}});

4.测试的时候 发现这样会导致滑动多次触发,所以优化代码如下


private int index = 0;// 滑动加载scrollView.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubswitch (event.getAction()) {case MotionEvent.ACTION_DOWN :break;case MotionEvent.ACTION_MOVE :index++;break;default :break;}if (event.getAction() == MotionEvent.ACTION_UP &&  index > 0) {index = 0;View view = ((ScrollView) v).getChildAt(0);if (view.getMeasuredHeight() <= v.getScrollY() + v.getHeight()) {//加载数据代码}}return false;}});


安卓开发论坛   http://www.eoeandroid.com/


原创粉丝点击