1.去写布局,加载更多的布局,构造方法
refresh_footer.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:gravity="center"
android:orientation="horizontal">
<ProgressBar
android:visibility="visible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:indeterminateDrawable="@drawable/custom_progress" />
<TextView
android:id="@+id/tv_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="加载更多..."
android:layout_marginLeft="8dp"
android:textColor="#ff0000"
android:textSize="25sp" />
</LinearLayout>
2.监听ListView的滑动,当滑动到底部的最后一条的时候,显示“加载更多”控件,设置状态,回调加载更多的接口
private boolean isLoadMore = false;//是否已经加载更多
private void initFooterView(Context context) {
footerView = View.inflate(context,R.layout.refresh_footer,null);
footerView.measure(0,0);
footerViewHeight = footerView.getHeight();
//默认是隐藏的
footerView.setPadding(0,-footerViewHeight,0,0);
//ListVeiw添加footer
addFooterView(footerView);
//监听ListView滑动到最后一条
setOnScrollListener(new MyOnScrollListener());
}
class MyOnScrollListener implements OnScrollListener{
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
//当静止或者惯性滚动的时候 SCROLL_STATE_IDLE:空闲的时候;SCROLL_STATE_FLING:惯性的时候
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE || scrollState == OnScrollListener.SCROLL_STATE_FLING){
//并且是最后一条可见
if (getLastVisiblePosition() >= getCount() - 1){//getCount() - 1 可以不用 - 1
//1.显示加载更多布局
footerView.setPadding(8,8,8,8);//写8是因为布局文件LinearLayout属性padding:8dp
//2.状态改变
isLoadMore = true;
//3.回调接口
if (mOnRefreshListener != null){
mOnRefreshListener.onLoadMore();
}
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
}
3.定义和回调接口
/**
* 监听控件的刷新
*/
public interface OnRefreshListener{
//当下拉刷新的时候回调这个方法
public void onPullDownRefresh();
//当加载更多的时候回调这个方法
public void onLoadMore();
}
public OnRefreshListener mOnRefreshListener;
//设置监听刷新,由外界设置
public void setOnRefreshListener(OnRefreshListener l){
this.mOnRefreshListener = l;
}
4.使用