通过实现setOnLoadMoreListener接口加载更多
public class LoadMoreListView extends ListView implements AbsListView.OnScrollListener {
private View mFootView;
private int mTotalItemCount;
private OnLoadMoreListener mLoadMoreListener;
private boolean mIsLoading = false;
public LoadMoreListView(Context context) {
super(context);
init(context);
}
public LoadMoreListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
public LoadMoreListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
mFootView = LayoutInflater.from(context).inflate(R.layout.footview, null);
setOnScrollListener(this);
}
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
// 滑到底部后自动加载更多,判断listview已经停止滚动并且最后可视的条目等于数据源的总条目
int lastVisibleIndex = listView.getLastVisiblePosition();
if (!mIsLoading && scrollState == OnScrollListener.SCROLL_STATE_IDLE
&& lastVisibleIndex == mTotalItemCount - 1) {
mIsLoading = true;
addFooterView(mFootView);
if (mLoadMoreListener != null) {
mLoadMoreListener.onLoadMore();
}
}
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
mTotalItemCount = totalItemCount;
}
public void setOnLoadMoreListener(OnLoadMoreListener listener) {
mLoadMoreListener = listener;
}
public void setLoadCompleted() {
mIsLoading = false;
removeFooterView(mFootView);
}
public interface OnLoadMoreListener {
void onLoadMore();
}
private static Field mFlingEndField = null;
private static Method mFlingEndMethod = null;
static {
try {
mFlingEndField = AbsListView.class.getDeclaredField("mFlingRunnable");
mFlingEndField.setAccessible(true);
mFlingEndMethod = mFlingEndField.getType().getDeclaredMethod("endFling");
mFlingEndMethod.setAccessible(true);
} catch (Exception e) {
mFlingEndMethod = null;
}
}
/**
* listView停止滑翔
* @param list
*/
public void stop(ListView list) {
if (mFlingEndMethod != null) {
try {
mFlingEndMethod.invoke(mFlingEndField.get(list));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
底部布局 R.layout.footview
<?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="match_parent"
android:background="#dedcdc"
android:gravity="center"
android:orientation="horizontal"
android:padding="15dp">
<ProgressBar
style="@android:style/Widget.ProgressBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="正在加载..."/>
</LinearLayout>
网友评论