Usare SwipeRefreshLayout in Kotlin

Mattepuffo's logo
Usare SwipeRefreshLayout in Kotlin

Usare SwipeRefreshLayout in Kotlin

SwipeRefreshLayout è un "componente" per Android per aggiornare i dati quando si fa il classico swipe-down.

Oggi vediamo un esempio usando Kotlin.

La prima cosa da fare è aggiungere una dipendenza a gradle:

dependencies {
	..........
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0'
}

A questo punto modifichiamo il layout aggiungendo lo SwipeRefreshLayout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swiperefresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</LinearLayout>

Infine nella nostra Activity:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        val refreshView = findViewById<SwipeRefreshLayout>(R.id.swiperefresh);

        getData();

      	refreshView.setOnRefreshListener(
            OnRefreshListener {
                getData();
                refreshView.setRefreshing(false);
            }
        )

    }

    fun getData() {
        // GET YOUR DATA
    }
}

Non bisogna fare altro.

Ovviamente ho omesso tutta la parte di creazione dei dati per la ListView, ecc.

Ma abbiamo visto tutto negli articoli precedenti.

Enjoy!


Condividi

Commentami!