在Android 开发中ListView 是常用控件,主要目的是为显示大批量数据。而 大批量数据一次加载显示容易造成内存溢出,需要分批加载。
而分批加载需要在加载下一页数据时提示用户等待更新,为此我参照网络上的资料。自行封装了一个带上拉更新的ListView。首先自定义的
ListView需要继承至ListView 并实现OnScrollListener接口。废话不多说,直接上源码。主要看MyPullUpListViewCallBack() 回调接口,当
listView滑动至底部时 调用。 当数据已完成时,调用 updateBottomView()提示用户已经没有更多的数据了.
1 public class MyPullUpListView extends ListView implements OnScrollListener { 2 3 /** 底部显示正在加载的页面 */ 4 private View footerView = null; 5 /** 存储上下文 */ 6 private Context context; 7 /** 上拉刷新的ListView的回调监听 */ 8 private MyPullUpListViewCallBack myPullUpListViewCallBack; 9 /** 记录第一行Item的数值 */ 10 private int firstVisibleItem; 11 12 public MyPullUpListView(Context context) { 13 super(context); 14 this.context = context; 15 initListView(); 16 } 17 18 public MyPullUpListView(Context context, AttributeSet attrs) { 19 super(context, attrs); 20 this.context = context; 21 initListView(); 22 } 23 24 /** 25 * 初始化ListView 26 */ 27 private void initListView() { 28 29 // 为ListView设置滑动监听 30 setOnScrollListener(this); 31 // 去掉底部分割线 32 setFooterDividersEnabled(false); 33 } 34 35 /** 36 * 初始化话底部页面 37 */ 38 public void initBottomView() { 39 40 if (footerView == null) { 41 footerView = LayoutInflater.from(this.context).inflate( 42 R.layout.listview_loadbar, null); 43 } 44 addFooterView(footerView); 45 } 46 47 //数据请求完成 没有更多 48 public void updateBottomView(){ 49 if (footerView != null){ 50 footerView.findViewById(R.id.footer_progressBar).setVisibility(GONE); 51 TextView tv = (TextView) footerView.findViewById(R.id.footer_text); 52 tv.setText("没有更多了"); 53 tv.setTextColor(getResources().getColor(R.color.black)); 54 } 55 } 56 57 public void onScrollStateChanged(AbsListView view, int scrollState) { 58 59 //当滑动到底部时 60 if (scrollState == OnScrollListener.SCROLL_STATE_IDLE 61 && firstVisibleItem != 0) { 62 myPullUpListViewCallBack.scrollBottomState(); 63 } 64 } 65 66 public void onScroll(AbsListView view, int firstVisibleItem, 67 int visibleItemCount, int totalItemCount) { 68 this.firstVisibleItem = firstVisibleItem; 69 70 if (footerView != null) { 71 //判断可视Item是否能在当前页面完全显示 72 if (visibleItemCount == totalItemCount) { 73 // removeFooterView(footerView); 74 footerView.setVisibility(View.GONE);//隐藏底部布局 75 } else { 76 // addFooterView(footerView); 77 footerView.setVisibility(View.VISIBLE);//显示底部布局 78 } 79 } 80 81 } 82 83 84 85 public void setMyPullUpListViewCallBack( 86 MyPullUpListViewCallBack myPullUpListViewCallBack) { 87 this.myPullUpListViewCallBack = myPullUpListViewCallBack; 88 } 89 90 /** 91 * 上拉刷新的ListView的回调监听 94 * 95 */ 96 public interface MyPullUpListViewCallBack { 97 98 void scrollBottomState(); 99 } 100 }