思路:在滑动基础上添加scrollview到底检测事件
1.首先检测是否滑动
- // 滑动加载
- scrollView.setOnTouchListener(new OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- // TODO Auto-generated method stub
- switch (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,"滑到底部");
- }
- // 滑动加载
- scrollView.setOnTouchListener(new OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- // TODO Auto-generated method stub
- switch (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() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- // TODO Auto-generated method stub
- switch (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/