How to implement Android Pull-to-Refresh How to implement Android Pull-to-Refresh android android

How to implement Android Pull-to-Refresh


Finally, Google released an official version of the pull-to-refresh library!

It is called SwipeRefreshLayout, inside the support library, and the documentation is here:

  1. Add SwipeRefreshLayout as a parent of view which will be treated as a pull to refresh the layout. (I took ListView as an example, it can be any View like LinearLayout, ScrollView etc.)

     <android.support.v4.widget.SwipeRefreshLayout     android:id="@+id/pullToRefresh"     android:layout_width="match_parent"     android:layout_height="wrap_content">     <ListView         android:id="@+id/listView"         android:layout_width="match_parent"         android:layout_height="match_parent"/> </android.support.v4.widget.SwipeRefreshLayout>
  2. Add a listener to your class

     protected void onCreate(Bundle savedInstanceState) {     final SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);     pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {         @Override         public void onRefresh() {             refreshData(); // your code             pullToRefresh.setRefreshing(false);         }     }); }

You can also call pullToRefresh.setRefreshing(true/false); as per your requirement.

UPDATE

Android support libraries have been deprecated and have been replaced by AndroidX. The link to the new library can be found here.

Also, you need to add the following dependency to your project:

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

OR

You can go to Refactor>>Migrate to AndroidX and Android Studio will handle the dependencies for you.


I've made an attempt to implement a pull to refresh component, it's far from complete but demonstrates a possible implementation, https://github.com/johannilsson/android-pulltorefresh.

Main logic is implemented in PullToRefreshListView that extends ListView. Internally it controls the scrolling of a header view using smoothScrollBy (API Level 8). The widget is now updated with support for 1.5 and later, please read the README for 1.5 support though.

In your layouts you simply add it like this.

<com.markupartist.android.widget.PullToRefreshListView    android:id="@+id/android:list"    android:layout_height="fill_parent"    android:layout_width="fill_parent"    />


I've also implemented a robust, open source, easy to use and highly customizable PullToRefresh library for Android. You can replace your ListView with the PullToRefreshListView as described in the documentation on the project page.

https://github.com/erikwt/PullToRefresh-ListView