ListView下拉重新整理,上拉自動載入更多
更新2016-2-19
程式碼下載地址已經更新。因為程式碼很久沒更新,已經很落伍了,建議大家使用RecyclerView實現。
參考專案:
https://github.com/bingoogolapple/BGARefreshLayout-Android
https://github.com/baoyongzhang/android-PullRefreshLayout
下拉重新整理,Android中非常普遍的功能。為了方便便重寫的ListView來實現下拉重新整理,同時添加了上拉自動載入更多的功能。設計最初是參考開源中國的Android客戶端原始碼。先看示例圖。
圖1 圖2
圖3 圖4
圖5 圖6
下拉重新整理的時動畫效果: 圖1 ==》 圖2 ==》 圖3 ==》 圖4 ==》 圖1。
上拉自動載入更多的效果:圖5
圖6是示例demo的截圖
重寫後的listview動畫效果來源於新增的頭部(header)和尾部(footer),listview提供了addHeaderView和addFooterView方法來新增header和footer。大家也可以通過修改頭部、尾部的xml檔案來定義自己的動畫效果。
實現原理
1.下拉重新整理
通過onTouchEvent判斷手勢,來改變listview的header。header的狀態共4種,自己定義為:
NONE(對應圖1):初始狀態
PULL(對應圖2):下拉狀態,此時鬆開會還原到狀態NONE,並不進行重新整理
RELEASE(對應圖3):同樣是下拉狀態,但此刻鬆開會執行重新整理,進入狀態REFRESHING
REFRESHING(對應圖4):正在執行重新整理,重新整理結束後進入狀態NONE。
header在四種狀態切換時不僅改變內部元件,同時改變自身的大小。改變內部元件的體現比如,箭頭的朝上或者朝下,文字提示的變化,等待圓圈的顯示與否。大小的改變其實就是高度的改變,NONE時header高度為0,RELEASE時header的高度由你下拉的程度決定。
2.載入更多
在listview滑動停止後,判斷listview的最後一個item是否已經顯示,如果顯示說明listview已經滑動到了最底部,這時便觸發載入更多的方法,方法結束根據結果改變footer。
3.回撥方法
在類中定義了兩個介面OnRefreshListener和OnLoadListener,用來定義和提供載入資料的方法,具體實現則交給它們的實現類去做。
示例程式碼
AutoListView.java
package com.example.autolistview.widget;
import com.example.autolistview.R;
import com.example.autolistview.utils.Utils;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
/**
* @author SunnyCoffee
* @create 2013-10-24
* @version 1.0
* @desc 自定義Listview 下拉重新整理,上拉載入更多
*/
public class AutoListView extends ListView implements OnScrollListener {
// 區分當前操作是重新整理還是載入
public static final int REFRESH = 0;
public static final int LOAD = 1;
// 區分PULL和RELEASE的距離的大小
private static final int SPACE = 20;
// 定義header的四種狀態和當前狀態
private static final int NONE = 0;
private static final int PULL = 1;
private static final int RELEASE = 2;
private static final int REFRESHING = 3;
private int state;
private LayoutInflater inflater;
private View header;
private View footer;
private TextView tip;
private TextView lastUpdate;
private ImageView arrow;
private ProgressBar refreshing;
private TextView noData;
private TextView loadFull;
private TextView more;
private ProgressBar loading;
private RotateAnimation animation;
private RotateAnimation reverseAnimation;
private int startY;
private int firstVisibleItem;
private int scrollState;
private int headerContentInitialHeight;
private int headerContentHeight;
// 只有在listview第一個item顯示的時候(listview滑到了頂部)才進行下拉重新整理, 否則此時的下拉只是滑動listview
private boolean isRecorded;
private boolean isLoading;// 判斷是否正在載入
private boolean loadEnable = true;// 開啟或者關閉載入更多功能
private boolean isLoadFull;
private int pageSize = 10;
private OnRefreshListener onRefreshListener;
private OnLoadListener onLoadListener;
public AutoListView(Context context) {
super(context);
initView(context);
}
public AutoListView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public AutoListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
// 下拉重新整理監聽
public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
this.onRefreshListener = onRefreshListener;
}
// 載入更多監聽
public void setOnLoadListener(OnLoadListener onLoadListener) {
this.loadEnable = true;
this.onLoadListener = onLoadListener;
}
public boolean isLoadEnable() {
return loadEnable;
}
// 這裡的開啟或者關閉載入更多,並不支援動態調整
public void setLoadEnable(boolean loadEnable) {
this.loadEnable = loadEnable;
this.removeFooterView(footer);
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
// 初始化元件
private void initView(Context context) {
// 設定箭頭特效
animation = new RotateAnimation(0, -180,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
animation.setInterpolator(new LinearInterpolator());
animation.setDuration(100);
animation.setFillAfter(true);
reverseAnimation = new RotateAnimation(-180, 0,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
reverseAnimation.setInterpolator(new LinearInterpolator());
reverseAnimation.setDuration(100);
reverseAnimation.setFillAfter(true);
inflater = LayoutInflater.from(context);
footer = inflater.inflate(R.layout.listview_footer, null);
loadFull = (TextView) footer.findViewById(R.id.loadFull);
noData = (TextView) footer.findViewById(R.id.noData);
more = (TextView) footer.findViewById(R.id.more);
loading = (ProgressBar) footer.findViewById(R.id.loading);
header = inflater.inflate(R.layout.pull_to_refresh_header, null);
arrow = (ImageView) header.findViewById(R.id.arrow);
tip = (TextView) header.findViewById(R.id.tip);
lastUpdate = (TextView) header.findViewById(R.id.lastUpdate);
refreshing = (ProgressBar) header.findViewById(R.id.refreshing);
// 為listview新增頭部和尾部,並進行初始化
headerContentInitialHeight = header.getPaddingTop();
measureView(header);
headerContentHeight = header.getMeasuredHeight();
topPadding(-headerContentHeight);
this.addHeaderView(header);
this.addFooterView(footer);
this.setOnScrollListener(this);
}
public void onRefresh() {
if (onRefreshListener != null) {
onRefreshListener.onRefresh();
}
}
public void onLoad() {
if (onLoadListener != null) {
onLoadListener.onLoad();
}
}
public void onRefreshComplete(String updateTime) {
lastUpdate.setText(this.getContext().getString(R.string.lastUpdateTime,
lastUpdate));
state = NONE;
refreshHeaderViewByState();
}
// 用於下拉重新整理結束後的回撥
public void onRefreshComplete() {
String currentTime = Utils.getCurrentTime();
onRefreshComplete(currentTime);
}
// 用於載入更多結束後的回撥
public void onLoadComplete() {
isLoading = false;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.firstVisibleItem = firstVisibleItem;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.scrollState = scrollState;
ifNeedLoad(view, scrollState);
}
// 根據listview滑動的狀態判斷是否需要載入更多
private void ifNeedLoad(AbsListView view, int scrollState) {
if (!loadEnable) {
return;
}
try {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
&& !isLoading
&& view.getLastVisiblePosition() == view
.getPositionForView(footer) && !isLoadFull) {
onLoad();
isLoading = true;
}
} catch (Exception e) {
}
}
/**
* 監聽觸控事件,解讀手勢
*/
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
if (firstVisibleItem == 0) {
isRecorded = true;
startY = (int) ev.getY();
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (state == PULL) {
state = NONE;
refreshHeaderViewByState();
} else if (state == RELEASE) {
state = REFRESHING;
refreshHeaderViewByState();
onRefresh();
}
isRecorded = false;
break;
case MotionEvent.ACTION_MOVE:
whenMove(ev);
break;
}
return super.onTouchEvent(ev);
}
// 解讀手勢,重新整理header狀態
private void whenMove(MotionEvent ev) {
if (!isRecorded) {
return;
}
int tmpY = (int) ev.getY();
int space = tmpY - startY;
int topPadding = space - headerContentHeight;
switch (state) {
case NONE:
if (space > 0) {
state = PULL;
refreshHeaderViewByState();
}
break;
case PULL:
topPadding(topPadding);
if (scrollState == SCROLL_STATE_TOUCH_SCROLL
&& space > headerContentHeight + SPACE) {
state = RELEASE;
refreshHeaderViewByState();
}
break;
case RELEASE:
topPadding(topPadding);
if (space > 0 && space < headerContentHeight + SPACE) {
state = PULL;
refreshHeaderViewByState();
} else if (space <= 0) {
state = NONE;
refreshHeaderViewByState();
}
break;
}
}
// 調整header的大小。其實調整的只是距離頂部的高度。
private void topPadding(int topPadding) {
header.setPadding(header.getPaddingLeft(), topPadding,
header.getPaddingRight(), header.getPaddingBottom());
header.invalidate();
}
/**
* 這個方法是根據結果的大小來決定footer顯示的。
* <p>
* 這裡假定每次請求的條數為10。如果請求到了10條。則認為還有資料。如過結果不足10條,則認為資料已經全部載入,這時footer顯示已經全部載入
* </p>
*
* @param resultSize
*/
public void setResultSize(int resultSize) {
if (resultSize == 0) {
isLoadFull = true;
loadFull.setVisibility(View.GONE);
loading.setVisibility(View.GONE);
more.setVisibility(View.GONE);
noData.setVisibility(View.VISIBLE);
} else if (resultSize > 0 && resultSize < pageSize) {
isLoadFull = true;
loadFull.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
more.setVisibility(View.GONE);
noData.setVisibility(View.GONE);
} else if (resultSize == pageSize) {
isLoadFull = false;
loadFull.setVisibility(View.GONE);
loading.setVisibility(View.VISIBLE);
more.setVisibility(View.VISIBLE);
noData.setVisibility(View.GONE);
}
}
// 根據當前狀態,調整header
private void refreshHeaderViewByState() {
switch (state) {
case NONE:
topPadding(-headerContentHeight);
tip.setText(R.string.pull_to_refresh);
refreshing.setVisibility(View.GONE);
arrow.clearAnimation();
arrow.setImageResource(R.drawable.pull_to_refresh_arrow);
break;
case PULL:
arrow.setVisibility(View.VISIBLE);
tip.setVisibility(View.VISIBLE);
lastUpdate.setVisibility(View.VISIBLE);
refreshing.setVisibility(View.GONE);
tip.setText(R.string.pull_to_refresh);
arrow.clearAnimation();
arrow.setAnimation(reverseAnimation);
break;
case RELEASE:
arrow.setVisibility(View.VISIBLE);
tip.setVisibility(View.VISIBLE);
lastUpdate.setVisibility(View.VISIBLE);
refreshing.setVisibility(View.GONE);
tip.setText(R.string.pull_to_refresh);
tip.setText(R.string.release_to_refresh);
arrow.clearAnimation();
arrow.setAnimation(animation);
break;
case REFRESHING:
topPadding(headerContentInitialHeight);
refreshing.setVisibility(View.VISIBLE);
arrow.clearAnimation();
arrow.setVisibility(View.GONE);
tip.setVisibility(View.GONE);
lastUpdate.setVisibility(View.GONE);
break;
}
}
// 用來計算header大小的。比較隱晦。
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
/*
* 定義下拉重新整理介面
*/
public interface OnRefreshListener {
public void onRefresh();
}
/*
* 定義載入更多介面
*/
public interface OnLoadListener {
public void onLoad();
}
}
這個類的邏輯複雜的地方就是header四種狀態的判斷和切換。
以下是幾種狀態的切換情況
NONE ==》 PULL
NONE 《== PULL ==》 RELEASE
PULL 《== RELEASE ==》 REFRESHING
REFRESHING ==》 NONE
程式碼中對於 RELEASE ==》PULL 狀態的切換處理的不太理想,好像是縱座標的記錄方式有問題,如果有誰解決,希望能夠留言告知。
為了減少篇幅,其他程式碼就不在貼了。
注意:定義header的xml最外層必須使用線性佈局,不然的話會出錯。
測試程式碼:點選下載(eclipse工程專案,編碼UTF-8)。由於程式碼涉及公司專案,所以提供的demo是自己新寫的。如圖6所示。
本篇會持續更新。