Recently, Google released a new version of the Support Library, which has an interesting component. It’s called SwipeRefreshLayout. With that, it’s become a child’s play to implement a quick Swipe-to-Refresh control for your apps.
A few things first
- Available only with android-support-v13. Which means that only apps target SDK level 13 and above can use this.
- It can only contain one scrollable direct child such as a ListView or a ScrollView.
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”${packageName}.${activityClass}” >
<android.support.v4.widget.SwipeRefreshLayout
android:id=”@+id/swipeLayout”
android:layout_width=”match_parent”
android:layout_height=”match_parent” >
<ListView
android:id=”@+id/listView”
android:layout_width=”match_parent”
android:layout_height=”match_parent” >
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
private void initializeViews() {
refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
refreshLayout.setOnRefreshListener(this);
// The default colors for the progress bar are not so nice.
setColorSchemeForProgressBar();
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
adapter.addAll(getDemoData(5));
listView.setAdapter(adapter);
}
The Refresh Task
@Override
public void onRefresh() {
Log.i(TAG, “Refresh Requested”);
doRefresh();
}
// Fetch data and update listview’s adapter
private void doRefresh() {
RefreshTask task = new RefreshTask();
task.execute((Void) null);
}
The Completion Work
private void postRefreshComplete() {
// Stop the refresh animation
refreshLayout.setRefreshing(false);
// Update adapter with new data
adapter.clear();
adapter.addAll(getDemoData(new Random().nextInt(20)));
adapter.notifyDataSetChanged();
}
And there you go, a simple swipe to refresh usage for your Android apps. You can find the whole source code here.