下拉刷新早期只能靠第三方客製控件,好用但偶爾會冒出難解的邊角問題。自從官方推出 SwipeRefreshLayout(Android Support Library v4)之後,這個功能就有了標準答案。本文示範如何用它包住 ListView 完成刷新。

結構非常單純,SwipeRefreshLayout 只能包一個可捲動的子檢視,這裡面放 ListView 即可(item 佈局只是一個 TextView,此處省略):
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
讓 Activity 實作 SwipeRefreshLayout.OnRefreshListener,註冊監聽並設定下拉時的進度圈配色:
public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener {
private SwipeRefreshLayout swipeLayout;
private ListView listView;
private ListViewAdapter adapter;
private List<Entity> list;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(R.color.materialBlue, R.color.materialGreen,
R.color.materialRed, R.color.materialYellow);
list = new ArrayList<Entity>();
for (int i = 0; i < 4; i++) {
list.add(new Entity("刷新"));
}
listView = (ListView) findViewById(R.id.list);
}
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
public void run() {
swipeLayout.setRefreshing(false);
list.add(new Entity("我們"));
adapter = new ListViewAdapter(MainActivity.this, list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}, 100000);
}
}
這裡有兩個關鍵點。第一,setColorScheme 決定刷新指示器的四段顏色,會依序循環顯示,可對齊品牌色系。第二,也是最容易漏掉的一點——資料處理完畢後必須呼叫 setRefreshing(false),否則刷新轉圈會一直轉下去。範例中用 100000 毫秒的延遲只是為了方便觀察效果,實作時應換成真正的網路請求回呼。
public class ListViewAdapter extends BaseAdapter {
private Context context;
private List<Entity> list;
public ListViewAdapter(Context context, List<Entity> list) {
this.context = context;
this.list = list;
}
public int getCount() {
return list.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int arg0) {
return 0;
}
public View getView(int position, View convertView, ViewGroup arg2) {
HolderView holderView;
if (convertView == null) {
holderView = new HolderView();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holderView.text = (TextView) convertView.findViewById(R.id.text);
convertView.setTag(holderView);
} else {
holderView = (HolderView) convertView.getTag();
}
Entity entity = list.get(position);
holderView.text.setText(entity.getText() + "");
return convertView;
}
class HolderView {
TextView text;
}
}
順帶修正一個常見疏漏:ViewHoldler 模式要在 convertView 為 null 時呼叫 setTag,並在重用時用 getTag 取回,範例原始寫法少了這一步,會導致 convertView 被回收後 text 為 null 而拋出例外。同時每次刷新都重建 adapter 也不理想,直接呼叫 notifyDataSetChanged 就好。
整體而言,SwipeRefreshLayout 的優勢在於穩定——手勢判定、閾值、動畫都交由系統處理,我們只需專注在「刷新時要做什麼」這件事上。