編輯:關於 Android 程式設計
幾乎每個專案都會用到列表的下拉刷新與上滑加載更多。過去大家最常用的是 pull-to-refresh 及其各種變種版本,而 Google 官方在 android.support.v4 套件中提供了全新的 SwipeRefreshLayout,地址在其 API 文件中,它正是官方的下拉刷新解決方案,動畫效果相當流暢。至於上拉加載更多,則可以透過自訂 ListView 來實現,思路也很簡單。

簡單介紹一下:
它本質上是一個 ViewGroup,但只允許容納一個子元件,子元件可以是任何 View。使用時,所在類別需實作 OnRefreshListener 介面,在 onRefresh() 方法中撰寫要完成的任務。
用 findViewById 取得 SwipeRefreshLayout 後,顯示刷新動畫呼叫 SwipeRefreshLayout.setRefreshing(true),取消則呼叫 setRefreshing(false),非常直觀。此外還有一些常用方法,例如透過 isShown() 判斷是否正在顯示刷新動畫。
佈局:
<com.example.listviewloadmore.loadmorelistview
android:id="@+id/listView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/hello_world">
</com.example.listviewloadmore.loadmorelistview>
思路是:監聽滑動事件並判斷是否已抵達底部,抵達底部時回呼我們自訂的方法,從而實現上拉加載。那具體怎麼監聽與回呼呢?不妨參考 Button 點擊事件的執行流程。Button 繼承自 TextView,TextView 又繼承自 View:
1. 實作 OnClickListener 介面並重寫 onClick 方法;
2. 透過 setOnClickListener 傳入監聽器。
查看 View 原始碼可知,View 類別中定義了 OnClickListener 介面與 setOnClickListener 方法。那麼在我們自訂的 ListView 中,步驟就非常清楚了:
1. 讓 MyListView 繼承 ListView;2. 實作 onLoadMore 介面;3. 在類別中宣告該介面物件;4. 提供 setOnLoadMore 方法;5. 在需要時呼叫 onLoadMore.loadMore 方法。
下面是 MyListView 原始碼:
package com.example.listviewloadmore;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
public class LoadMoreListView extends ListView implements OnScrollListener {
private View footer;
private int totalItem;
private int lastItem;
private boolean isLoading;
private OnLoadMore onLoadMore;
public LoadMoreListView(Context context) {
super(context);
init(context);
}
public LoadMoreListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public LoadMoreListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
LayoutInflater inflater = LayoutInflater.from(context);
footer = inflater.inflate(R.layout.load_more_footer, null, false);
footer.setVisibility(View.GONE);
this.addFooterView(footer);
this.setOnScrollListener(this);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.lastItem = firstVisibleItem + visibleItemCount;
this.totalItem = totalItemCount;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (this.totalItem == lastItem && scrollState == SCROLL_STATE_IDLE) {
if (!isLoading) {
isLoading = true;
footer.setVisibility(View.VISIBLE);
onLoadMore.loadMore();
}
}
}
public void setLoadMoreListen(OnLoadMore onLoadMore) {
this.onLoadMore = onLoadMore;
}
/** 加載完成調用此方法 */
public void onLoadComplete() {
footer.setVisibility(View.GONE);
isLoading = false;
}
public interface OnLoadMore {
public void loadMore();
}
}
程式碼並不複雜,仔細看就能明白。底部「正在加載」的佈局如下:
<RelativeLayout android:id="@+id/load_more_footer" android:layout_height="wrap_content" android:layout_width="fill_parent" xmlns:android="https://schemas.android.com/apk/res/android">
<LinearLayout android:layout_centerInParent="true" android:layout_height="wrap_content" android:layout_width="wrap_content">
<ProgressBar android:id="@+id/load_more_progressBar" android:layout_height="36dp" android:layout_width="36dp" android:padding="3dp" android:visibility="visible">
<TextView android:gravity="center" android:id="@+id/no_more_textView" android:layout_height="36dp" android:layout_width="wrap_content" android:text="正在加載" android:textColor="#666666" android:textSize="16sp" android:visibility="visible">
</TextView>
</ProgressBar>
</LinearLayout>
</RelativeLayout>
至此,上拉加載更多就完成了。接下來把下拉與上拉結合起來使用。
佈局檔 activity_main.xml:
<RelativeLayout android:layout_height="match_parent" android:layout_width="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.listviewloadmore.MainActivity"
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools">
<com.example.listviewloadmore.loadmorelistview
android:id="@+id/listView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/hello_world">
</com.example.listviewloadmore.loadmorelistview>
</RelativeLayout>
MainActivity 程式碼:
package com.example.listviewloadmore;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.example.listviewloadmore.LoadMoreListView.OnLoadMore;
public class MainActivity extends Activity implements OnRefreshListener, OnLoadMore {
private LoadMoreListView listView;
private SwipeRefreshLayout swip;
private int page = 1;
ArrayList<String> data1 = new ArrayList<String>();
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData(1);
}
private void initView() {
listView = (LoadMoreListView) findViewById(R.id.listView);
listView.setLoadMoreListen(this);
swip = (SwipeRefreshLayout) findViewById(R.id.swip_index);
swip.setOnRefreshListener(this);
swip.setColorSchemeResources(
android.R.color.holo_blue_light,
android.R.color.holo_red_light,
android.R.color.holo_orange_light,
android.R.color.holo_green_light);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data1);
}
private void initData(int page2) {
if (page2 == 1) {
for (int i = 0; i < 10; i++) {
data1.add((i + 1) + "");
}
listView.setAdapter(adapter);
} else {
data1.add("新加的第" + (9 + page2) + "個");
}
}
// 下拉刷新
@Override
public void onRefresh() {
Toast.makeText(this, "開始刷新啦", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (swip.isShown()) {
swip.setRefreshing(false);
}
Toast.makeText(MainActivity.this, "刷新完成了", Toast.LENGTH_SHORT).show();
}
}, 3000);
}
// 加載更多
@Override
public void loadMore() {
page++;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
initData(page);
listView.onLoadComplete();
Toast.makeText(MainActivity.this, "加載完成", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
}, 3000);
}
}
效果圖如下:


解決 Android ADT 的 Monitor Thread 與 loopback connection 錯誤
錯誤現象ADT 啟動時若出現 Failed to initialize Monitor Thread 或 Unable to establish loopback con
EasyDialog:輕量友善的氣泡提示框庫完整解析
GitHub 上這個相當清爽的 Dialog 值得一用,動畫效果帶點 Q 彈的手感,適合拿來做提示氣泡。 效果預覽: 一、引入方式 compile com.gith
React Native Android 篇:Touch 事件源碼原理與五種按壓狀態效果實作
Native 相比 Hybrid 或 H5 最大的優勢,就在於流暢且複雜的互動效果,觸摸事件正是其中的核心,包含點擊(Click)、長按(LongClick)與手勢(Ge
Android 在一個 Activity 中實現多個 ListView 共享滾動條
當我們直接在佈局檔中放三個 ListView 時,會出現三個滾動條,而且每個 ListView 都只顯示一個 item,必須拖動才會顯示更多。要如何改善呢? 做法是有