編輯:關於Android編程
前面寫過一篇關於下拉刷新控件的文章下拉刷新控件終結者:PullToRefreshLayout,後來看到好多人還有上拉加載更多的需求,於是就在前面下拉刷新控件的基礎上進行了改進,加了上拉加載的功能。不僅如此,我已經把它改成了對所有View都通用!可以隨心所欲使用這兩個功能~~
我做了一個大集合的demo,實現了ListView、GridView、ExpandableListView、ScrollView、WebView、ImageView、TextView的下拉刷新和上拉加載。後面會提供demo的下載地址,最新代碼已上傳到github:https://github.com/jingchenUSTC/PullToRefreshAndLoad
依照慣例,下面將會是一大波效果圖:
demo首頁也是可下拉的ListView,在底下可以加入table:
ListView:
GridView:
ExpandableListView:
ScrollView:
WebView:
ImageView:
TextView:
很不錯吧?最後的ImageView和TextView是最簡單的,直接在下面的接口方法裡返回true。
增加上拉加載很簡單,和管理下拉頭一樣,再多管理一個上拉頭,也不費事;至於把它改成通用的就需要統一一下View的行為了,為此,我定義了這樣一個接口:
package com.jingchen.pulltorefresh.pullableview;
public interface Pullable
{
/**
* 判斷是否可以下拉,如果不需要下拉功能可以直接return false
*
* @return true如果可以下拉否則返回false
*/
boolean canPullDown();
/**
* 判斷是否可以上拉,如果不需要上拉功能可以直接return false
*
* @return true如果可以上拉否則返回false
*/
boolean canPullUp();
}
從接口名就可以看出它是一個提供判斷是否可拉的方法的接口。這個接口的兩個方法,canPullDown()是判斷何時可以下拉的方法,canPullUp()則是判斷何時可以上拉,我在demo中的判斷是滑到頂部的時候可以下拉,滑到底部的時候可以上拉。所有需要上拉和下拉的View都需要實現這個接口。後面會給出一些View的實現。先來看看改進後的自定義的布局PullToRefreshLayout,增加了一個上拉頭,下拉頭和上拉頭之間的View是實現了Pullable接口的pullableView。相比前面的版本,這裡有改動的需要注意的地方如下:
1、增加了上拉頭,相應的也增加了控制變量。
2、拉動時消除content_view事件防止誤觸發不再使用反射,直接設置 event.setAction(MotionEvent.ACTION_CANCEL)。
3、消除了拉動過程中的多點觸碰導致的劇變。
4、不再設置content_view的onTouListener,讓使用者可以更加自由的設置監聽器。
這個PullToRefreshLayout只負責管理三個控件,如果一個View需要有上拉下拉功能則只需實現接口就行了。下面看PullToRefreshLayout的代碼,注釋寫了好多:
package com.jingchen.pulltorefresh; import java.util.Timer; import java.util.TimerTask; import android.content.Context; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.graphics.Shader.TileMode; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.RelativeLayout; import android.widget.TextView; import com.jingchen.pulltorefresh.pullableview.Pullable; /** * 自定義的布局,用來管理三個子控件,其中一個是下拉頭,一個是包含內容的pullableView(可以是實現Pullable接口的的任何View), * 還有一個上拉頭 * * @author 陳靖 */ public class PullToRefreshLayout extends RelativeLayout { public static final String TAG = "PullToRefreshLayout"; // 初始狀態 public static final int INIT = 0; // 釋放刷新 public static final int RELEASE_TO_REFRESH = 1; // 正在刷新 public static final int REFRESHING = 2; // 釋放加載 public static final int RELEASE_TO_LOAD = 3; // 正在加載 public static final int LOADING = 4; // 操作完畢 public static final int DONE = 5; // 當前狀態 private int state = INIT; // 刷新回調接口 private OnRefreshListener mListener; // 刷新成功 public static final int SUCCEED = 0; // 刷新失敗 public static final int FAIL = 1; // 按下Y坐標,上一個事件點Y坐標 private float downY, lastY; // 下拉的距離。注意:pullDownY和pullUpY不可能同時不為0 public float pullDownY = 0; // 上拉的距離 private float pullUpY = 0; // 釋放刷新的距離 private float refreshDist = 200; // 釋放加載的距離 private float loadmoreDist = 200; private MyTimer timer; // 回滾速度 public float MOVE_SPEED = 8; // 第一次執行布局 private boolean isLayout = false; // 在刷新過程中滑動操作 private boolean isTouch = false; // 手指滑動距離與下拉頭的滑動距離比,中間會隨正切函數變化 private float radio = 2; // 下拉箭頭的轉180°動畫 private RotateAnimation rotateAnimation; // 均勻旋轉動畫 private RotateAnimation refreshingAnimation; // 下拉頭 private View refreshView; // 下拉的箭頭 private View pullView; // 正在刷新的圖標 private View refreshingView; // 刷新結果圖標 private View refreshStateImageView; // 刷新結果:成功或失敗 private TextView refreshStateTextView; // 上拉頭 private View loadmoreView; // 上拉的箭頭 private View pullUpView; // 正在加載的圖標 private View loadingView; // 加載結果圖標 private View loadStateImageView; // 加載結果:成功或失敗 private TextView loadStateTextView; // 實現了Pullable接口的View private View pullableView; // 過濾多點觸碰 private int mEvents; // 這兩個變量用來控制pull的方向,如果不加控制,當情況滿足可上拉又可下拉時沒法下拉 private boolean canPullDown = true; private boolean canPullUp = true; /** * 執行自動回滾的handler */ Handler updateHandler = new Handler() { @Override public void handleMessage(Message msg) { // 回彈速度隨下拉距離moveDeltaY增大而增大 MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2 / getMeasuredHeight() * (pullDownY + Math.abs(pullUpY)))); if (!isTouch) { // 正在刷新,且沒有往上推的話則懸停,顯示"正在刷新..." if (state == REFRESHING && pullDownY <= refreshDist) { pullDownY = refreshDist; timer.cancel(); } else if (state == LOADING && -pullUpY <= loadmoreDist) { pullUpY = -loadmoreDist; timer.cancel(); } } if (pullDownY > 0) pullDownY -= MOVE_SPEED; else if (pullUpY < 0) pullUpY += MOVE_SPEED; if (pullDownY < 0) { // 已完成回彈 pullDownY = 0; pullView.clearAnimation(); // 隱藏下拉頭時有可能還在刷新,只有當前狀態不是正在刷新時才改變狀態 if (state != REFRESHING && state != LOADING) changeState(INIT); timer.cancel(); } if (pullUpY > 0) { // 已完成回彈 pullUpY = 0; pullUpView.clearAnimation(); // 隱藏下拉頭時有可能還在刷新,只有當前狀態不是正在刷新時才改變狀態 if (state != REFRESHING && state != LOADING) changeState(INIT); timer.cancel(); } // 刷新布局,會自動調用onLayout requestLayout(); } }; public void setOnRefreshListener(OnRefreshListener listener) { mListener = listener; } public PullToRefreshLayout(Context context) { super(context); initView(context); } public PullToRefreshLayout(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public PullToRefreshLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(context); } private void initView(Context context) { timer = new MyTimer(updateHandler); rotateAnimation = (RotateAnimation) AnimationUtils.loadAnimation( context, R.anim.reverse_anim); refreshingAnimation = (RotateAnimation) AnimationUtils.loadAnimation( context, R.anim.rotating); // 添加勻速轉動動畫 LinearInterpolator lir = new LinearInterpolator(); rotateAnimation.setInterpolator(lir); refreshingAnimation.setInterpolator(lir); } private void hide() { timer.schedule(5); } /** * 完成刷新操作,顯示刷新結果。注意:刷新完成後一定要調用這個方法 */ /** * @param refreshResult * PullToRefreshLayout.SUCCEED代表成功,PullToRefreshLayout.FAIL代表失敗 */ public void refreshFinish(int refreshResult) { refreshingView.clearAnimation(); refreshingView.setVisibility(View.GONE); switch (refreshResult) { case SUCCEED: // 刷新成功 refreshStateImageView.setVisibility(View.VISIBLE); refreshStateTextView.setText(R.string.refresh_succeed); refreshStateImageView .setBackgroundResource(R.drawable.refresh_succeed); break; case FAIL: default: // 刷新失敗 refreshStateImageView.setVisibility(View.VISIBLE); refreshStateTextView.setText(R.string.refresh_fail); refreshStateImageView .setBackgroundResource(R.drawable.refresh_failed); break; } // 刷新結果停留1秒 new Handler() { @Override public void handleMessage(Message msg) { changeState(DONE); hide(); } }.sendEmptyMessageDelayed(0, 1000); } /** * 加載完畢,顯示加載結果。注意:加載完成後一定要調用這個方法 * * @param refreshResult * PullToRefreshLayout.SUCCEED代表成功,PullToRefreshLayout.FAIL代表失敗 */ public void loadmoreFinish(int refreshResult) { loadingView.clearAnimation(); loadingView.setVisibility(View.GONE); switch (refreshResult) { case SUCCEED: // 加載成功 loadStateImageView.setVisibility(View.VISIBLE); loadStateTextView.setText(R.string.load_succeed); loadStateImageView.setBackgroundResource(R.drawable.load_succeed); break; case FAIL: default: // 加載失敗 loadStateImageView.setVisibility(View.VISIBLE); loadStateTextView.setText(R.string.load_fail); loadStateImageView.setBackgroundResource(R.drawable.load_failed); break; } // 刷新結果停留1秒 new Handler() { @Override public void handleMessage(Message msg) { changeState(DONE); hide(); } }.sendEmptyMessageDelayed(0, 1000); } private void changeState(int to) { state = to; switch (state) { case INIT: // 下拉布局初始狀態 refreshStateImageView.setVisibility(View.GONE); refreshStateTextView.setText(R.string.pull_to_refresh); pullView.clearAnimation(); pullView.setVisibility(View.VISIBLE); // 上拉布局初始狀態 loadStateImageView.setVisibility(View.GONE); loadStateTextView.setText(R.string.pullup_to_load); pullUpView.clearAnimation(); pullUpView.setVisibility(View.VISIBLE); break; case RELEASE_TO_REFRESH: // 釋放刷新狀態 refreshStateTextView.setText(R.string.release_to_refresh); pullView.startAnimation(rotateAnimation); break; case REFRESHING: // 正在刷新狀態 pullView.clearAnimation(); refreshingView.setVisibility(View.VISIBLE); pullView.setVisibility(View.INVISIBLE); refreshingView.startAnimation(refreshingAnimation); refreshStateTextView.setText(R.string.refreshing); break; case RELEASE_TO_LOAD: // 釋放加載狀態 loadStateTextView.setText(R.string.release_to_load); pullUpView.startAnimation(rotateAnimation); break; case LOADING: // 正在加載狀態 pullUpView.clearAnimation(); loadingView.setVisibility(View.VISIBLE); pullUpView.setVisibility(View.INVISIBLE); loadingView.startAnimation(refreshingAnimation); loadStateTextView.setText(R.string.loading); break; case DONE: // 刷新或加載完畢,啥都不做 break; } } /** * 不限制上拉或下拉 */ private void releasePull() { canPullDown = true; canPullUp = true; } /* * (非 Javadoc)由父控件決定是否分發事件,防止事件沖突 * * @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent) */ @Override public boolean dispatchTouchEvent(MotionEvent ev) { switch (ev.getActionMasked()) { case MotionEvent.ACTION_DOWN: downY = ev.getY(); lastY = downY; timer.cancel(); mEvents = 0; releasePull(); break; case MotionEvent.ACTION_POINTER_DOWN: case MotionEvent.ACTION_POINTER_UP: // 過濾多點觸碰 mEvents = -1; break; case MotionEvent.ACTION_MOVE: if (mEvents == 0) { if (((Pullable) pullableView).canPullDown() && canPullDown && state != LOADING) { // 可以下拉,正在加載時不能下拉 // 對實際滑動距離做縮小,造成用力拉的感覺 pullDownY = pullDownY + (ev.getY() - lastY) / radio; if (pullDownY < 0) { pullDownY = 0; canPullDown = false; canPullUp = true; } if (pullDownY > getMeasuredHeight()) pullDownY = getMeasuredHeight(); if (state == REFRESHING) { // 正在刷新的時候觸摸移動 isTouch = true; } } else if (((Pullable) pullableView).canPullUp() && canPullUp && state != REFRESHING) { // 可以上拉,正在刷新時不能上拉 pullUpY = pullUpY + (ev.getY() - lastY) / radio; if (pullUpY > 0) { pullUpY = 0; canPullDown = true; canPullUp = false; } if (pullUpY < -getMeasuredHeight()) pullUpY = -getMeasuredHeight(); if (state == LOADING) { // 正在加載的時候觸摸移動 isTouch = true; } } else releasePull(); } else mEvents = 0; lastY = ev.getY(); // 根據下拉距離改變比例 radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight() * (pullDownY + Math.abs(pullUpY)))); requestLayout(); if (pullDownY <= refreshDist <span > </span>&& (state == RELEASE_TO_REFRESH || state == DONE)) { <span > </span>// 如果下拉距離沒達到刷新的距離且當前狀態是釋放刷新,改變狀態為下拉刷新 <span > </span>changeState(INIT); <span > </span>} <span > </span>if (pullDownY >= refreshDist && (state == INIT || state == DONE)) { <span > </span>// 如果下拉距離達到刷新的距離且當前狀態是初始狀態刷新,改變狀態為釋放刷新 <span > </span>changeState(RELEASE_TO_REFRESH); <span > </span>} <span > </span>// 下面是判斷上拉加載的,同上,注意pullUpY是負值 <span > </span>if (-pullUpY <= loadmoreDist <span > </span>&& (state == RELEASE_TO_LOAD || state == DONE)) { <span > </span>changeState(INIT); <span > </span>} <span > </span>if (-pullUpY >= loadmoreDist && (state == INIT || state == DONE)) { <span > </span>changeState(RELEASE_TO_LOAD); <span > </span>} // 因為刷新和加載操作不能同時進行,所以pullDownY和pullUpY不會同時不為0,因此這裡用(pullDownY + // Math.abs(pullUpY))就可以不對當前狀態作區分了 if ((pullDownY + Math.abs(pullUpY)) > 8) { // 防止下拉過程中誤觸發長按事件和點擊事件 ev.setAction(MotionEvent.ACTION_CANCEL); } break; case MotionEvent.ACTION_UP: if (pullDownY > refreshDist || -pullUpY > loadmoreDist) // 正在刷新時往下拉(正在加載時往上拉),釋放後下拉頭(上拉頭)不隱藏 isTouch = false; if (state == RELEASE_TO_REFRESH) { changeState(REFRESHING); // 刷新操作 if (mListener != null) mListener.onRefresh(this); } else if (state == RELEASE_TO_LOAD) { changeState(LOADING); // 加載操作 if (mListener != null) mListener.onLoadMore(this); } hide(); default: break; } // 事件分發交給父類 super.dispatchTouchEvent(ev); return true; } private void initView() { // 初始化下拉布局 pullView = refreshView.findViewById(R.id.pull_icon); refreshStateTextView = (TextView) refreshView .findViewById(R.id.state_tv); refreshingView = refreshView.findViewById(R.id.refreshing_icon); refreshStateImageView = refreshView.findViewById(R.id.state_iv); // 初始化上拉布局 pullUpView = loadmoreView.findViewById(R.id.pullup_icon); loadStateTextView = (TextView) loadmoreView .findViewById(R.id.loadstate_tv); loadingView = loadmoreView.findViewById(R.id.loading_icon); loadStateImageView = loadmoreView.findViewById(R.id.loadstate_iv); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (!isLayout) { // 這裡是第一次進來的時候做一些初始化 refreshView = getChildAt(0); pullableView = getChildAt(1); loadmoreView = getChildAt(2); isLayout = true; initView(); refreshDist = ((ViewGroup) refreshView).getChildAt(0) .getMeasuredHeight(); loadmoreDist = ((ViewGroup) loadmoreView).getChildAt(0) .getMeasuredHeight(); } // 改變子控件的布局,這裡直接用(pullDownY + pullUpY)作為偏移量,這樣就可以不對當前狀態作區分 refreshView.layout(0, (int) (pullDownY + pullUpY) - refreshView.getMeasuredHeight(), refreshView.getMeasuredWidth(), (int) (pullDownY + pullUpY)); pullableView.layout(0, (int) (pullDownY + pullUpY), pullableView.getMeasuredWidth(), (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight()); loadmoreView.layout(0, (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight(), loadmoreView.getMeasuredWidth(), (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight() + loadmoreView.getMeasuredHeight()); } class MyTimer { private Handler handler; private Timer timer; private MyTask mTask; public MyTimer(Handler handler) { this.handler = handler; timer = new Timer(); } public void schedule(long period) { if (mTask != null) { mTask.cancel(); mTask = null; } mTask = new MyTask(handler); timer.schedule(mTask, 0, period); } public void cancel() { if (mTask != null) { mTask.cancel(); mTask = null; } } class MyTask extends TimerTask { private Handler handler; public MyTask(Handler handler) { this.handler = handler; } @Override public void run() { handler.obtainMessage().sendToTarget(); } } } /** * 刷新加載回調接口 * * @author chenjing * */ public interface OnRefreshListener { /** * 刷新操作 */ void onRefresh(PullToRefreshLayout pullToRefreshLayout); /** * 加載操作 */ void onLoadMore(PullToRefreshLayout pullToRefreshLayout); } }
上面就是整個布局的代碼,並不是很難。
下面看各個View對Pullable接口的實現,ListView和GridView還有ExpandableListView的判斷方法是一樣的:
PullableListView:
package com.jingchen.pulltorefresh.pullableview; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.widget.ListView; public class PullableListView extends ListView implements Pullable { public PullableListView(Context context) { super(context); } public PullableListView(Context context, AttributeSet attrs) { super(context, attrs); } public PullableListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean canPullDown() { if (getCount() == 0) { // 沒有item的時候也可以下拉刷新 return true; } else if (getFirstVisiblePosition() == 0 && getChildAt(0).getTop() >= 0) { // 滑到ListView的頂部了 return true; } else return false; } @Override public boolean canPullUp() { if (getCount() == 0) { // 沒有item的時候也可以上拉加載 return true; } else if (getLastVisiblePosition() == (getCount() - 1)) { // 滑到底部了 if (getChildAt(getLastVisiblePosition() - getFirstVisiblePosition()) != null && getChildAt( getLastVisiblePosition() - getFirstVisiblePosition()).getBottom() <= getMeasuredHeight()) return true; } return false; } }
PullableExpandableListView:
package com.jingchen.pulltorefresh.pullableview; import android.content.Context; import android.util.AttributeSet; import android.widget.ExpandableListView; public class PullableExpandableListView extends ExpandableListView implements Pullable { public PullableExpandableListView(Context context) { super(context); } public PullableExpandableListView(Context context, AttributeSet attrs) { super(context, attrs); } public PullableExpandableListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean canPullDown() { if (getCount() == 0) { // 沒有item的時候也可以下拉刷新 return true; } else if (getFirstVisiblePosition() == 0 && getChildAt(0).getTop() >= 0) { // 滑到頂部了 return true; } else return false; } @Override public boolean canPullUp() { if (getCount() == 0) { // 沒有item的時候也可以上拉加載 return true; } else if (getLastVisiblePosition() == (getCount() - 1)) { // 滑到底部了 if (getChildAt(getLastVisiblePosition() - getFirstVisiblePosition()) != null && getChildAt( getLastVisiblePosition() - getFirstVisiblePosition()).getBottom() <= getMeasuredHeight()) return true; } return false; } }
PullableGridView:
package com.jingchen.pulltorefresh.pullableview; import android.content.Context; import android.util.AttributeSet; import android.widget.GridView; public class PullableGridView extends GridView implements Pullable { public PullableGridView(Context context) { super(context); } public PullableGridView(Context context, AttributeSet attrs) { super(context, attrs); } public PullableGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean canPullDown() { if (getCount() == 0) { // 沒有item的時候也可以下拉刷新 return true; } else if (getFirstVisiblePosition() == 0 && getChildAt(0).getTop() >= 0) { // 滑到頂部了 return true; } else return false; } @Override public boolean canPullUp() { if (getCount() == 0) { // 沒有item的時候也可以上拉加載 return true; } else if (getLastVisiblePosition() == (getCount() - 1)) { // 滑到底部了 if (getChildAt(getLastVisiblePosition() - getFirstVisiblePosition()) != null && getChildAt( getLastVisiblePosition() - getFirstVisiblePosition()).getBottom() <= getMeasuredHeight()) return true; } return false; } }
PullableScrollView:
package com.jingchen.pulltorefresh.pullableview; import android.content.Context; import android.util.AttributeSet; import android.widget.ScrollView; public class PullableScrollView extends ScrollView implements Pullable { public PullableScrollView(Context context) { super(context); } public PullableScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public PullableScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean canPullDown() { if (getScrollY() == 0) return true; else return false; } @Override public boolean canPullUp() { if (getScrollY() >= (getChildAt(0).getHeight() - getMeasuredHeight())) return true; else return false; } }
PullableWebView:
package com.jingchen.pulltorefresh.pullableview; import android.content.Context; import android.util.AttributeSet; import android.webkit.WebView; public class PullableWebView extends WebView implements Pullable { public PullableWebView(Context context) { super(context); } public PullableWebView(Context context, AttributeSet attrs) { super(context, attrs); } public PullableWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean canPullDown() { if (getScrollY() == 0) return true; else return false; } @Override public boolean canPullUp() { if (getScrollY() >= getContentHeight() * getScale() - getMeasuredHeight()) return true; else return false; } }
ImageView和TextView就不貼了,我直接在方法裡返回了true。
源碼下載:通用版下拉刷新上拉加載大合集demo
精彩專題分享:javascriptAndroid加載功能匯總
本文已經被整理到《Android下拉刷新上拉加載效果》,歡迎大家學習研究。
希望本文所述對大家學習Android下拉刷新上拉加載控件有所幫助。
先上圖:這裡以添加 afinal_0.5.1_bin.jar 為例。第一步:添加jar包到libs裡面,系統自動把jar加載到android private librar
系統權限 在運行時請求權限系統權限 Android是一個權限分離的操作系統,每個應用使用不同的系統身份運行(Linux用戶ID和群組ID)。系統的不同部分也被分隔進不同
1、事務2、命令行操作數據庫
layout_height的作用:首先按照聲明的尺寸分配,剩余的空間再按照layout_weight進行分配一平均分配:代碼:<code class="h