项目中遇到了这样一种类似于ListView的需求:使用ScrollView分页显示数据,滑动到最后的时候自动加载下一页。如果是ListView我们可以判断当前显示的last item,从而得知是否已经滑动到最后,而ScrollView并没有提供这样一种方法,甚至不能添加OnScrollListener。那么我们该如何处理呢?综合参考了网友们的方法,我总结除了如下的实现形式:
1、实现自己的ScrollView
复制代码
2、在布局文件中引用自定义的ScrollView
我的ScrollView中添加了一个TextView用来显示字符串。代码终身略号代表包路径。
复制代码
3、在activity中进行相应处理,主要就是分页加载的处理。此处未列出完整文件,只展示了使用自定义ScrollView的代码。
复制代码
参考网址:
http://www.aoandroid.com/node/9101
http://www.iteye.com/problems/71100
1、实现自己的ScrollView
- import android.content.Context;
- import android.util.AttributeSet;
- import android.widget.ScrollView;
- public class ControlableScrollView extends ScrollView {
- //自定义的监听器,当满足条件时调用
- private OnScrollListener mListener;
- public ControlableScrollView(Context context) {
- super(context);
- }
- public ControlableScrollView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
- public ControlableScrollView(Context context, AttributeSet attrs,
- int defStyle) {
- super(context, attrs, defStyle);
- }
- //覆盖父类的方法,当scroll时调用,可判断是否已经滑到最后,computeVerticalScrollRange方法用于获取ScrollView的总高度
- @Override
- protected void onScrollChanged(int l, int t, int oldl, int oldt) {
- super.onScrollChanged(l, t, oldl, oldt);
- if (mListener != null
- && getHeight() + getScrollY() >= computeVerticalScrollRange()) {
- mListener.onScroll(this);
- }
- }
- //添加监听
- public void setOnScrollListener(OnScrollListener onScrollListener) {
- this.mListener = onScrollListener;
- }
- //自定义的监听接口,满足条件是调用其中的方法,执行相应的操作
- public static interface OnScrollListener {
- /**
- * called when the view scrolled to the bottom edge.
- *
- * @param v
- * ControlableScrollView
- */
- public void onScroll(ControlableScrollView v);
- }
- }
2、在布局文件中引用自定义的ScrollView
我的ScrollView中添加了一个TextView用来显示字符串。代码终身略号代表包路径。
- <...ControlableScrollView
- android:id="@+id/log_scroll"
- android:layout_width="match_parent"
- android:layout_height="200dp"
- android:layout_alignParentBottom="true"
- android:layout_below="@id/log_expanded_title" >
- <TextView
- android:id="@+id/log_text"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:textSize="13sp" />
- </...ControlableScrollView>
- private ControlableScrollView mScrollView;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.g_transbomb_view);
- mScrollView = findViewById(R.id.log_scroll);
- mScrollView.setOnScrollListener(new OnScrollListener() {
- @Override
- public void onScroll(ControlableScrollView v) {
- //执行到此处,说明ScrollView已经滑动到最后,可进行相应的处理。
- }
- }
- }
- });
- }
参考网址:
http://www.aoandroid.com/node/9101
http://www.iteye.com/problems/71100