본문 바로가기
Development/Android

[android] SwipeRefreshLayout 간단하게 사용하기

by Sonagiya 2021. 3. 29.
반응형
  • 라이브러리 추가하기
dependencies {
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
}

 

  • 새로고침이 필요한 레이아웃 감싸기
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

 

  • 새로고침 리스너 달기, 데이터 세팅하기, 새로고침 완료 세팅하기
class MainActivity : AppCompatActivity() {
    var count: Int = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textView = findViewById<TextView>(R.id.text)
        val refresh = findViewById<SwipeRefreshLayout>(R.id.refresh)
        refresh.setOnRefreshListener {
            refresh.postDelayed({
                textView.text = "refresh ${count++}"
                refresh.isRefreshing = false
            }, 2000)
        }
    }
}

 

  • 테스트 동영상

 

반응형

댓글