Android provides SwipeRefreshLayout to implement pull to refresh functionality in Android. We can use it for RecyclerView, ListView, or other types of views. In this tutorial, I will explain how you can implement Pull To Refresh for RecyclerView using SwipeRefreshLayout in Android.

The following is the Java code for pull to refresh functionality. If you are looking for a Kotlin solution, please have a look at, Implement Pull To Refresh in Kotlin.
Import Androidx library for SwipeRefreshLayout
In your App level build.gradle
file, add the following dependencies under the dependencies block, and sync your project.
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.gridlayout:gridlayout:1.0.0'
XML Code: Wrap RecyclerView inside SwipeRefreshLayout
Now to implement Pull to Refresh functionality, we need to put RecyclerView layout inside SwipeRefreshLayout in the XML code as shown in the following code.
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipe_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Activity Code in Java
Now inside your Activity or Fragment’s onCreate method add the following code. initializeRefreshListener()
method will set a listener to the SwipeRefreshLayout
and will call onRefresh()
method, whenever pull to refresh operation is performed by the user.
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.os.Handler;
public class MainActivity extends AppCompatActivity {
private SwipeRefreshLayout swipeRefreshLayout;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
swipeRefreshLayout = findViewById(R.id.swipe_layout);
initializeRefreshListener();
}
void initializeRefreshListener() {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// This method gets called when user pull for refresh,
// You can make your API call here,
// We are using adding a delay for the moment
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}
}, 3000);
}
});
}
In onRefresh()
method you can make your API call to get the latest data. In the above code, we just added a delay. When data refresh is done we need to call SwipeRefreshLayout.setRefreshing(false);
method explicitly to dismiss the loading view.