public class RefreshLayout extends SwipeRefreshLayout implements AbsListView.OnScrollListener {
private int mTouchSlop; //滑动最短距离
private int mDownY; //按下时的Y坐标
private int mLastY; //抬起时的Y坐标
private boolean isLoading = false; //是否处于加载状态
private ListView mListView; //布局内的ListView实例
private View mListViewFooter; //上拉加载脚布局
private OnLoadMoreListener onLoadMoreListener; //上拉加载监听
public RefreshLayout(Context context) {
this(context, null);
}
public RefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mListViewFooter = LayoutInflater.from(context).inflate(R.layout.view_load_more_footer, null, false);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
//初始化布局内的ListView对象
if (mListView == null) {
getListView();
}
}
/**
* 获取布局内的ListView对象
*/
private void getListView() {
int childCount = getChildCount();
if (childCount > ) {
View childView = getChildAt();
if (childView instanceof ListView) {
mListView = (ListView) childView;
//设置滚动监听器给ListView, 使得滚动的情况下也可以自动加载
mListView.setOnScrollListener(this);
}
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mDownY = (int) ev.getRawY();
break;
case MotionEvent.ACTION_MOVE:
mLastY = (int) ev.getRawY();
break;
case MotionEvent.ACTION_UP:
if (canLoadMore()) {
LoadMore();
}
break;
}
return super.dispatchTouchEvent(ev);
}
/**
* 处理加载更多
*/
private void LoadMore() {
if (onLoadMoreListener != null) {
//设置上拉加载时的状态
setLoading(true);
onLoadMoreListener.onLoadMore();
}
}
/**
* 设置上拉加载时的状态
*/
public void setLoading(boolean loading) {
isLoading = loading;
if (isLoading) {
mListView.addFooterView(mListViewFooter);
} else {
mListView.removeFooterView(mListViewFooter);
mDownY = ;
mLastY = ;
}
}
/**
* 是否满足上拉加载条件
*/
private boolean canLoadMore() {
return isBottom() && !isLoading && isPullUp();
}
/**
* ListView是否滑倒最底部
*/
private boolean isBottom() {
if (mListView != null && mListView.getAdapter() != null) {
return mListView.getLastVisiblePosition() == (mListView.getAdapter().getCount() - );
}
return false;
}
/**
* 是否是上拉操作
*/
private boolean isPullUp() {
return mLastY == ? false : (mDownY - mLastY) >= mTouchSlop;
}
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
if (canLoadMore()) {
LoadMore();
}
}
/**
* 上拉加载监听接口
*/
public interface OnLoadMoreListener {
void onLoadMore();
}
/**
* 设置监听
*/
public void setOnLoadMoreListener(OnLoadMoreListener listener) {
this.onLoadMoreListener = listener;
}
}