編輯:關於 Android 程式設計
本文將一步步講解如何在 Android 中實現帶動態效果的下拉刷新列表,文末思路完整、代碼齊全。
1. 下拉刷新的實現原理
2. 自定義 Android 控件,重寫 ListView
3. ScrollListener 滾動監聽
4. Adapter 適配器的使用
先看一眼最終效果:


先看這一步的效果:

我們要實現的是帶下拉刷新效果的 ListView,因此選擇自定義重寫原生 ListView。先寫一個繼承它的類,暫時不加具體實現:
public class RefreshListView extends ListView {
public RefreshListView(Context context) {
super(context);
}
public RefreshListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RefreshListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
接著定義列表項的布局 listview_item.xml,這裡只放一個 ImageView 和一個 TextView,你可以發揮創意做得更豐富:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textSize="25sp" />
</LinearLayout>
由於自定義了 ListView,主界面布局也要相應替換成自定義類的完整路徑:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.mylistviewrefresh.refreshlistview.RefreshListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000"
android:dividerHeight="5dip" />
</RelativeLayout>
主角 MainActivity 這裡重點說明適配器的使用:
public class MainActivity extends Activity {
private RefreshListView listView;
private SimpleAdapter simple_adapter;
private List<Map<String, Object>> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (RefreshListView) findViewById(R.id.listview);
iniData(); // 初始化 20 條數據
/**
* SimpleAdapter 五個參數含義:
* 1. context 上下文
* 2. 顯示用的數據,即 map 的 list
* 3. Item 的布局
* 4. map 中的鍵值(與第 5 個參數一一對應)
* 5. 布局中控件 id 的數組
*/
simple_adapter = new SimpleAdapter(MainActivity.this, list, R.layout.listview_item,
new String[]{"image", "text"},
new int[]{R.id.image, R.id.text});
listView.setAdapter(simple_adapter);
}
private List<Map<String, Object>> iniData() {
list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
Map<String, Object> map = new HashMap<>();
map.put("text", i);
map.put("image", R.drawable.ic_launcher);
list.add(map);
}
return list;
}
}
先說說下拉刷新的實現思路:我們平常用到的下拉刷新,都是在下拉後於屏幕上方顯示一些原本隱藏的控件(如下拉箭頭、進度條)。這些控件不能簡單地設為 invisible,因為它們的顯示有一個漸變過程。
所以做法是:加入一個隱藏的頭部布局放在屏幕上方,根據下拉的距離來實時調整它的顯示狀態。
新建 header.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dip"
android:paddingBottom="10dip">
<LinearLayout
android:id="@+id/layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/tip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下拉可以刷新!" />
<TextView
android:id="@+id/lastupdate_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:id="@+id/arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dip"
android:layout_toLeftOf="@id/layout"
android:src="@drawable/pull_to_refresh_arrow" />
<ProgressBar
android:id="@+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dip"
android:layout_toLeftOf="@id/layout"
android:visibility="gone" />
</RelativeLayout>
</LinearLayout>
這個頭部包含提示語、更新時間、下拉箭頭圖片,以及一個刷新時才顯示的 ProgressBar(現在隱藏)。接著改寫 RefreshListView,把 header 加進去並通過負的 padding 把它藏到屏幕外:
public class RefreshListView extends ListView {
View header; // 頂部布局
int headerHeight; // 頂部布局高度
public RefreshListView(Context context) {
super(context);
initView(context);
}
public RefreshListView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public RefreshListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
/** 初始化界面,添加頂部布局 */
private void initView(Context context) {
LayoutInflater inflater = LayoutInflater.from(context);
header = inflater.inflate(R.layout.header, null);
measureView(header);
headerHeight = header.getMeasuredHeight();
topPadding(-headerHeight); // 用負 padding 把 header 藏起來
this.addHeaderView(header);
}
/** 手動測量 header 的寬高 */
private void measureView(View view) {
ViewGroup.LayoutParams p = view.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int width = ViewGroup.getChildMeasureSpec(0, 0, p.width);
int height;
int tempHeight = p.height;
if (tempHeight > 0) {
height = MeasureSpec.makeMeasureSpec(tempHeight, MeasureSpec.EXACTLY);
} else {
height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
view.measure(width, height);
}
/** 設置 header 的上邊距 */
private void topPadding(int topPadding) {
header.setPadding(header.getPaddingLeft(), topPadding,
header.getPaddingRight(), header.getPaddingBottom());
header.invalidate();
}
}
把 topPadding(-headerHeight) 注釋掉,就能看到 header 顯示出來;保留它,header 便被巧妙隱藏。
思路是同時添加觸摸監聽與滾動監聽:
觸摸監聽:在 ACTION_DOWN 時記錄起點 Y 值 startY,在 ACTION_MOVE 中根據當前 Y 與 startY 的差值判斷下拉距離,與臨界值比較,得出當前狀態——下拉、釋放或刷新,並據此刷新 header 顯示。ACTION_UP 時根據狀態決定是否觸發刷新。
滾動監聽:判斷列表是否在頂端(第一個可見 item 的 position 是否為 0),以及跟蹤滾動狀態。
我們在自定義 ListView 中定義一個 IRefreshListener 接口,由 MainActivity 實現,用於刷新時更新數據。完整代碼如下:
public class RefreshListView extends ListView implements OnScrollListener {
View header;
int headerHeight;
int firstVisibleItem; // 第一個可見 item 的位置
int scrollState; // 當前滾動狀態
boolean isRemark; // 是否在頂端按下
int startY; // 按下時的 Y 值
int state; // 當前狀態
final int NONE = 0; // 正常
final int PULL = 1; // 提示下拉
final int RELEASE = 2; // 提示釋放
final int REFRESHING = 3; // 刷新中
IRefreshListener iRefreshListener;
public RefreshListView(Context context) { super(context); initView(context); }
public RefreshListView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); }
public RefreshListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(context); }
private void initView(Context context) {
LayoutInflater inflater = LayoutInflater.from(context);
header = inflater.inflate(R.layout.header, null);
measureView(header);
headerHeight = header.getMeasuredHeight();
topPadding(-headerHeight);
this.addHeaderView(header);
this.setOnScrollListener(this);
}
private void measureView(View view) {
ViewGroup.LayoutParams p = view.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int width = ViewGroup.getChildMeasureSpec(0, 0, p.width);
int height;
int tempHeight = p.height;
if (tempHeight > 0) {
height = MeasureSpec.makeMeasureSpec(tempHeight, MeasureSpec.EXACTLY);
} else {
height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
view.measure(width, height);
}
private void topPadding(int topPadding) {
header.setPadding(header.getPaddingLeft(), topPadding,
header.getPaddingRight(), header.getPaddingBottom());
header.invalidate();
}
@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;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
if (firstVisibleItem == 0) {
isRemark = true;
startY = (int) ev.getY();
}
break;
case MotionEvent.ACTION_MOVE:
onMove(ev);
break;
case MotionEvent.ACTION_UP:
if (state == RELEASE) {
state = REFRESHING;
refreshViewByState();
iRefreshListener.onRefresh(); // 觸發加載數據
} else if (state == PULL) {
state = NONE;
isRemark = false;
refreshViewByState();
}
break;
}
return super.onTouchEvent(ev);
}
private void onMove(MotionEvent ev) {
if (!isRemark) {
return;
}
int tempY = (int) ev.getY();
int space = tempY - startY;
int topPadding = space - headerHeight;
switch (state) {
case NONE:
if (space > 0) {
state = PULL;
refreshViewByState();
}
break;
case PULL:
topPadding(topPadding);
if (space > headerHeight + 30 && scrollState == SCROLL_STATE_TOUCH_SCROLL) {
state = RELEASE;
refreshViewByState();
}
break;
case RELEASE:
topPadding(topPadding);
if (space < headerHeight + 30) {
state = PULL;
refreshViewByState();
}
break;
}
}
/** 根據當前狀態改變界面顯示 */
private void refreshViewByState() {
TextView tip = (TextView) header.findViewById(R.id.tip);
ImageView arrow = (ImageView) header.findViewById(R.id.arrow);
ProgressBar progress = (ProgressBar) header.findViewById(R.id.progress);
RotateAnimation anim = new RotateAnimation(0, 180,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(500);
anim.setFillAfter(true);
RotateAnimation anim1 = new RotateAnimation(180, 0,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
anim1.setDuration(500);
anim1.setFillAfter(true);
switch (state) {
case NONE:
arrow.clearAnimation();
topPadding(-headerHeight);
break;
case PULL:
arrow.setVisibility(View.VISIBLE);
progress.setVisibility(View.GONE);
tip.setText("下拉可以刷新!");
arrow.clearAnimation();
arrow.setAnimation(anim1);
break;
case RELEASE:
arrow.setVisibility(View.VISIBLE);
progress.setVisibility(View.GONE);
tip.setText("釋放可以刷新!");
arrow.clearAnimation();
arrow.setAnimation(anim);
break;
case REFRESHING:
topPadding(50);
arrow.setVisibility(View.GONE);
progress.setVisibility(View.VISIBLE);
tip.setText("正在刷新...");
arrow.clearAnimation();
break;
}
}
/** 數據加載完成後調用 */
public void refreshComplete() {
state = NONE;
isRemark = false;
refreshViewByState();
TextView lastupdatetime = (TextView) header.findViewById(R.id.lastupdate_time);
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
Date date = new Date(System.currentTimeMillis());
lastupdatetime.setText(format.format(date));
}
public void setInterface(IRefreshListener iRefreshListener) {
this.iRefreshListener = iRefreshListener;
}
/** 刷新數據接口 */
public interface IRefreshListener {
void onRefresh();
}
}
最後,MainActivity 實現 IRefreshListener 接口,在回調裡模擬異步刷新並添加數據:
public class MainActivity extends Activity implements RefreshListView.IRefreshListener {
private RefreshListView listView;
private SimpleAdapter simple_adapter;
private List<Map<String, Object>> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (RefreshListView) findViewById(R.id.listview);
iniData();
simple_adapter = new SimpleAdapter(MainActivity.this, list, R.layout.listview_item,
new String[]{"image", "text"},
new int[]{R.id.image, R.id.text});
listView.setAdapter(simple_adapter);
listView.setInterface(this); // 設置刷新接口
}
private List<Map<String, Object>> iniData() {
list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
Map<String, Object> map = new HashMap<>();
map.put("text", i);
map.put("image", R.drawable.ic_launcher);
list.add(map);
}
return list;
}
/** 接口回調:在 RefreshListView 中調用此方法刷新數據 */
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Map<String, Object> map = new HashMap<>();
map.put("text", "滾動添加");
map.put("image", R.drawable.ic_launcher);
list.add(0, map);
simple_adapter.notifyDataSetChanged();
listView.refreshComplete();
}
}, 2000); // 延遲兩秒,模擬網絡請求,便於觀察刷新效果
}
}
至此,開頭展示的下拉刷新效果就完整實現了。回顧整個思路:先自定義重寫 ListView,加入一個用負 padding 隱藏起來的 header;再通過觸摸監聽計算下拉距離、切換下拉/釋放/刷新等狀態並實時刷新 header;最後借助接口回調把刷新事件交給 Activity 去更新數據。掌握這套套路後,你便能輕鬆為各類列表加上流暢的下拉刷新體驗。
Android RecyclerView 點擊事件實作解析
一、為什麼要用 RecyclerView 自從 Android L 問世,RecyclerView 就逐步取代 ListView 成為展示大量資料的首選。相比 ListV
小米手環怎麼接入微信?開啟步數與排行榜推送
把小米手環接到微信之後,可以直接在微信裡查步數、看排行,不必每次切換 App。設定步驟如下。 先在手机上打开小米手环,点击右上角的「更多」图标。 在選項清單中點擊「服務
以 RecyclerView 打造高擴展性列表菜單
在許多 App 中,例如個人中心、發現頁、動態頁,常見到縱向排列的列表式菜單。這類畫面看似簡單,但若要在分割線、間距、群組與動畫上保持彈性,就需要更靈活的列表實作方式。常
自定義圓形漸變刻度進度條:Android 繪圖實戰
普通的圓形進度條到處都有,但只要加上漸變配色與刻度,質感就差很多。本文示範如何從零畫一個帶刻度、漸變色的圓環進度條。 一、畫出圓環 核心 API 是 drawArc: