1. 程式人生 > >自定義SwipeRefreshLayout實現上拉載入更多並自帶系統的下拉重新整理

自定義SwipeRefreshLayout實現上拉載入更多並自帶系統的下拉重新整理

/**
 * Created by lzy on 2017/6/6 0006.
 */
public class MySwipeRefreshLayout extends SwipeRefreshLayout{
    private final TextView mFooterView;
    ListView view;
    OnListScrollListener listener;
    boolean isLoading;//判斷當前layout是否在載入中,防止非同步操作導致載入中再重複載入
boolean isShowing;//判斷底部載入欄是否需要顯示
Context mContext;
    public 
MySwipeRefreshLayout(Context context) { super(context); mContext = context; mFooterView = new TextView(mContext); mFooterView.setText("正在載入中"); mFooterView.setGravity(Gravity.CENTER); mFooterView.setTextSize(22); } public MySwipeRefreshLayout(Context context, AttributeSet attrs) { super
(context, attrs); mContext = context; mFooterView = new TextView(mContext); mFooterView.setText("正在載入中"); mFooterView.setGravity(Gravity.CENTER); mFooterView.setTextSize(22); } @Override protected void onLayout(boolean changed, int left, int top, int
right, int bottom) { super.onLayout(changed, left, top, right, bottom); if(view ==null){ if(getChildAt(0)instanceof ListView){ view = (ListView)getChildAt(0); } } } /** * 在分發事件的時候處理子控制元件的觸控事件 * * @param ev * @return */ private float mDownY, mUpY, lastFloat ; @Override public boolean dispatchTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: // 移動的起點 mDownY = ev.getY(); break; case MotionEvent.ACTION_MOVE: float mMoveY = ev.getY(); // 移動過程中判斷時候能上拉載入更多 if (isLoadMore()&&!isShowing&&lastFloat>mMoveY+5) { // 載入資料 setShowing(true); } lastFloat = mMoveY; break; case MotionEvent.ACTION_UP: // 移動的終點 mUpY = getY(); if (isShowing) { // 載入資料 if(listener!=null){ isLoading = true; listener.Refresh(); } } lastFloat = 0; break; } return super.dispatchTouchEvent(ev); } /** * 設定載入狀態,是否載入傳入boolean值進行判斷 * * @param showing */ public void setShowing(boolean showing) { isShowing = showing; if (isShowing) { // 顯示佈局 view.addFooterView(mFooterView); } else { // 隱藏佈局 view.removeFooterView(mFooterView); // 重置滑動的座標 mDownY = 0; mUpY = 0; isLoading = showing; } } private synchronized boolean isLoadMore() { boolean isLast = view.getLastVisiblePosition() == view.getAdapter().getCount()-1; return isLast&&!isLoading; } public void setOnListScrollListener(OnListScrollListener listener){ this.listener = listener; } public interface OnListScrollListener{ void Refresh(); } }