📌 Intro
종합설계 과목을 진행하면서 만든 앱에서 Retrofit을 통해 서버로부터 데이터를 받아오는 작업을 진행했다. 이 때 서버로 보낸 영상을 처리하느라 조회 페이지에 들어갔을 때 나오지 않았던 데이터들을 새로고침 기능을 통해 가져오려고 했다. 당근마켓과 같은 앱을 사용할 때 화면을 아래로 당기면 리스트가 새로고침되는 것을 본 적이 있을 것이다. 이 기능을 어떻게 만드는지에 대해 알아보도록 하자.
📌 Swipe Refresh Layout
SwipeRefreshLayout은 사용자가 수직으로 화면을 당겨 contents를 새로고침 할 때 사용하는 View다. 이 뷰를 초기화하는 액티비티에서 OnRefreshListener를 추가해야 한다. SwipeRefreshLayout은 사용자 제스처가 실행될 때마다 Listener에게 이를 알리고 Listener는 새로고침을 정확히 언제 실행할 지 결정한다.
SwipeRefreshLayout은 제스처의 결과로 새로고침될 뷰의 부모로 만들어야 하며 하나의 자식만 지원할 수 있다.
Listener가 새로 고침이 없어야 한다고 결정하면 setRefreshing(false)을 호출하여 새로 고침의 시각적 표시를 취소할 것이다. 만약 프로그레스 애니메이션을 보여주길 원한다면 setRefreshing(true)을 호출해야 한다.
📌 사용방법
<?xml version="1.0" encoding="utf-8"?>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/resourceRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
swiperefreshlayout으로 recyclerView를 감싸주었다.
SwipeRefreshLayout에 OnRefreshListener를 등록한 코드는 다음과 같다. 자세한 내용은 주석 번호에 맞게 적어두었다.
binding.swipeLayout.setOnRefreshListener {
// 1
resourceList.add("hello")
binding.resourceRecyclerView.adapter!!.notifyDataSetChanged()
// 2
binding.swipeLayout.isRefreshing = false
}
1. 새로고침 시 진행할 코드를 작성한다. 위 예에서는 어댑터의 리스트에 "hello"를 추가해주고 리사이클러뷰의 어댑터에게 값이 변경되었다고 알리는 작업을 했다.
2. 새로고침 완료시 새로고침 아이콘이 사라질 수 있도록 isRefreshing을 false로 변경해준다.
📌 참고
[1] https://kimyunseok.tistory.com/133
[2] https://salix97.tistory.com/218
[3] https://developer.android.com/reference/androidx/swiperefreshlayout/widget/package-summary