Implementing Pull to Refresh for RecyclerView
apply plugin: 'com.android.application'
//...
dependencies {
// ...
compile 'com.android.support:support-v4:25.3.1'
}
allprojects {
repositories {
// add below
maven { url "https://maven.google.com" }
}
}
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipeContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/rvItems"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</android.support.v4.widget.SwipeRefreshLayout>
public class TimelineActivity extends Activity {
private SwipeRefreshLayout swipeContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Only ever call `setContentView` once right at the top
setContentView(R.layout.activity_main);
// Lookup the swipe container view
swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
// Setup refresh listener which triggers new data loading
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// Your code to refresh the list here.
// Make sure you call swipeContainer.setRefreshing(false)
// once the network request has completed successfully.
fetchTimelineAsync(0);
}
});
// Configure the refreshing colors
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
public void fetchTimelineAsync(int page) {
// Send the network request to fetch the updated data
// `client` here is an instance of Android Async HTTP
// getHomeTimeline is an example endpoint.
client.getHomeTimeline(new JsonHttpResponseHandler() {
public void onSuccess(JSONArray json) {
// Remember to CLEAR OUT old items before appending in the new ones
adapter.clear();
// ...the data has come back, add new items to your adapter...
adapter.addAll(...);
// Now we call setRefreshing(false) to signal refresh has finished
swipeContainer.setRefreshing(false);
}
public void onFailure(Throwable e) {
Log.d("DEBUG", "Fetch timeline error: " + e.toString());
}
});
}
}
References
http://guides.codepath.com/android/implementing-pull-to-refresh-guide