본문 바로가기
앱 제작/키워드 알림 앱

SwipeRefreshLayout :: 당겨서 새로고침 하기

by Kim Juhwan 2021. 1. 9.

1. SwipeRefreshLayout란?
2. xml 소스 코드
3. activity 소스 코드

 

 


 

 

1. SwipeRefreshLayout란?

목록 업데이트가 너무 빨라서 티가 안나넹...

 

앱에서 게시물 목록을 당겨서 새로고침 할 때 사용하는 것이 바로 SwipeRefreshLayout이다.

화면을 당기면 빙글빙글 돌아가는 애니메이션이 뜨면서

setOnRefreshListener를 호출하게 되는데, 이때 리스너 안에 새로고침을 하기 위한 코드를 작성해 넣으면 된다.

 

나는 게시물 목록을 당길 때 목록이 손가락을 따라 같이 이동하다가

탁! 놓으면 새로고침 애니메이션이 빙글빙글 돌아가기를 원했는데

기본으로 제공되는 SwipeRefreshLayout은 그런 기능이 없는 듯하다.

따로 오픈 라이브러리를 사용하던가 해야 할 것 같다.

(위 영상을 보면 알겠지만 화면을 당겨도 목록이 움직이지는 않는다)

 

2021-01-10 +)

내가 딱 원하는 라이브러리를 발견했다. 사용방법도 거의 똑같고 애니메이션도 여러개 지원한다.

 

baoyongzhang/android-PullRefreshLayout

This component like SwipeRefreshLayout, it is more beautiful than SwipeRefreshLayout. - baoyongzhang/android-PullRefreshLayout

github.com

 

 

2. xml 소스 코드

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".fragments.home.HomeFragment">

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

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView_notices"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</LinearLayout>

간단하다.

SwipeRefreshLayout 안에다가 RecyclerView를 넣으면 된다.

 

 

 

3. activity 소스 코드

        refresh_layout.setOnRefreshListener {
            notices.clear() // 리스트를 한 번 비워주고
            crawler.activateBot(page) // 리스트에 값을 넣어주고
            keywordAdapter!!.notifyDataSetChanged() // 새로고침 하고
            refresh_layout.isRefreshing = false // 새로고침을 완료하면 아이콘을 없앤다.
        }

SwipeRefreshLayout에 setOnRefreshListener를 달아준다.

화면을 당기면 새로고침 애니메이션과 함께 이 리스너가 호출된다.

이제 리스너 안에 코드를 작성해 넣으면 된다.

 

  1. 리스트를 비운다
  2. 리스트에 값을 넣는다
  3. 새로고침 한다
  4. 새로고침 아이콘을 없앤다.

이 순서대로 코드를 작성하면 된다.

cralwe.activateBot(page) 이 부분은 개인적으로 만든 함수이니 각자 본인이 코드를 구현해주면 된다.

notifyDataSetChanged는 어댑터에게 데이터가 변경되었으니 새로고침을 하라고 알려주는 메서드이고

isRefreshing은 값을 false로 주면 빙글빙글 돌아가는 아이콘이 없어진다.

 

 

 


 

 

▼ 무한 스크롤도 배워보면 어떨까요? ▼

 

 

[코틀린] infinite/endless scroll(무한 스크롤)과 recyclerView

1. infinite/endless scroll  1-1. 개념  1-2. Progress Bar  1-3. 아이템 뷰(ItemView)  1-4. 홀더(Holder)  1-5. 스크롤 리스너(Scroll Listener) 2. Adapter  1-1. 전체 소스  1-2. 코드 설명 3. Activ..

todaycode.tistory.com

 

 

Icons made by Kiranshastry from www.flaticon.com

반응형

댓글