Swipe Refresh Implementation in Android Studio


Hello there everyone,

This week we are going to see, how to implement the swipe up refresh button using Android Studio.

In the following tutorial, I’ll be swipe refreshing the web view layout in the app.

XML:

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

    <WebView
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:visibility="gone" />

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

JAVA – MainActivity:

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private SwipeRefreshLayout layoutRefresh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        layoutRefresh = this.findViewById(R.id.swipeLayout);

        layoutRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (webView.getUrl() != null) {
                    webView.reload(); // write what happens after swipe refreshing
                }
                layoutRefresh.setRefreshing(false); //this line hides the refresh button after completing
            }
        });
}

GRADLE – App:

apply plugin: 'com.android.application'

android {
    android.defaultConfig.vectorDrawables.useSupportLibrary = true
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.whysurfswim.wss"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 4
        versionName '4.0'
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.0.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:27.0.2'
    testCompile 'junit:junit:4.12'
}

NOTE:

ADD REFRESH BUTTON TO MAKE IT LOOK PROFESSIONAL