Last updated on January 9th, 2020 at 12:36 pm

Android Swipe Refresh is a latest feature added to android support library with lots of feature and new layouts. It is a standard way to refresh layout with swipe in android.

Swipe Refresh Layout is a group layout with the particularity that it can only hold one scrollable view as a child. This layout handel touch event and shows indeterminate progress animation below the action bar when the user swipes down. You can easily find this view in some of latest google app, facebook and twitter etc.. Swipe Refresh contain few method :

Methods:

– setOnRefreshListener(OnRefreshListener): adds a listener to let other parts of the code know when refreshing begins.
– setRefreshing(boolean): enables or disables progress visibility.
– isRefreshing(): checks whether the view is refreshing.
– setColorScheme(): it receive four different colors that will be used to colorize the animation.

SwipeRefresh Layout:

Layout of swipe is very simple you need to add scroll bar or a list view. I am using scrollview for this example:

<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:gravity="center"
            android:text="@string/refresh" />
    </ScrollView>

</android.support.v4.widget.SwipeRefreshLayout>

 Code in Activity:

We need few line of code to get thing work. We just need to get the layout and assign some color to progress bar and the listener. When user swipe down the layout we need handler to handle the request and using postDelayed() method we run some process in background and display progress bar for some time in taskbar.

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		final SwipeRefreshLayout swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

		swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
				android.R.color.holo_green_light,
				android.R.color.holo_orange_light,
				android.R.color.holo_red_light);

		swipeLayout
				.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
					@Override
					public void onRefresh() {
						new Handler().postDelayed(new Runnable() {
							@Override
							public void run() {
								swipeLayout.setRefreshing(false);
							}
						}, 5000);
					}
				});
	}

And after implementing this code or Swipe Refresh Layout is ready to work. You can download this code from above link Thankyou.

Happy Coding.