[Android / Kotlin] Swiperefreshlayout

Subeen·2023년 3월 16일
0

Android

목록 보기
13/71
post-thumbnail

본 포스팅에서는 Swiperefreshlayout를 사용하여 아래로 당겼을 때 화면이 새로고침 되는 예제를 만들어 보려고 한다. RecyclerView와 CardView를 사용하여 아이템 리스트 목록을 보여주고 화면이 새로고침 될 때마다 리스트의 요소들을 랜덤하게 재배열 하여 보여주고자 한다. RecyclerView와 CardView는 이전에 구현 한 예제를 사용한다.

📍 결과 동영상

  • 화면을 아래로 당길 때 새로고침 아이콘이 화면에 표시되며 리스트 목록이 재배열 되어 변경 된 리스트 목록이 표시된다.
  • 새로고침 작업이 끝나면 새로고침 아이콘이 사라진다.

📍 앱에 종속성 추가

Swiperefreshlayout을 사용하기 위해서는 먼저 앱 수준의 Gradle 파일에서 라이브러리 종속 항목을 추가한다.

dependencies {
	// CardView
	implementation "androidx.cardview:cardview:1.0.0"
    
    // Swiperefreshlayout
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
}

📍 Swiperefreshlayout 사용하기

👩🏻‍💻 SwipeRefreshLayout 생성하기

💡 SwipeRefreshLayout을 먼저 만들고 refresh를 적용 할 뷰를 레이아웃 내부에 정의한다.

  • activity_card_view.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>

    <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=".cardview.CardViewActivity">

        <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:id="@+id/refreshLayout"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

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

        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

👩🏻‍💻 RecyclerView 아이템 생성하기

  • item_cardview.xml

📌 CardView 위젯 속성

  • card_view:cardCornerRadius : 레이아웃에서 모서리 반경을 설정
  • CardView.setRadius : 코드에서 모서리 반경을 설정
  • card_view:cardBackgroundColor : 카드뷰의 배경색 설정
  • card_view:cardElevation : 카드뷰 아래에 그림자를 그린다.
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_margin="10dp"
    android:padding="10dp"
    app:cardCornerRadius="12dp"
    app:cardElevation="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageArea"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.7"
            android:scaleType="centerCrop" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_margin="10dp"
            android:layout_weight="0.3"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/titleArea"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/amountArea"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:bufferType="spannable"
                android:textColor="@color/black"
                android:textSize="12sp" />

        </LinearLayout>
    </LinearLayout>
</androidx.cardview.widget.CardView>

👩🏻‍💻 데이터 모델 생성하기

  • CardModel.kt
data class CardModel(
    val title: String, val amount: String, val image: Int
)

👩🏻‍💻 RecyclerView Adapter 생성하기

  • CardviewAdapter.kt
class CardviewAdapter(val items: MutableList<CardModel>) :
    RecyclerView.Adapter<CardviewAdapter.ViewHolder>() {
    // View Holder를 생성하고 View를 붙여주는 역할의 메서드
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardviewAdapter.ViewHolder {
        val v =
            LayoutInflater.from(parent.context).inflate(R.layout.item_cardview, parent, false)
        return ViewHolder(v)
    }

	// 생성된 View Holder에 데이터를 바인딩 해주는 메서드
    override fun onBindViewHolder(holder: CardviewAdapter.ViewHolder, position: Int) {
        holder.bindItems(items[position])
    }

	// 데이터의 개수 반환하는 메서드
    override fun getItemCount(): Int {
        return items.count()
    }

	// 화면에 표시 될 뷰를 저장하는 역할
    // 뷰를 재활용 하기 위해 각 요소를 저장해두고 사용한다.
    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bindItems(items: CardModel) {
            val imageArea = itemView.findViewById<ImageView>(R.id.imageArea)
            val amountArea = itemView.findViewById<TextView>(R.id.amountArea)
            val titleArea = itemView.findViewById<TextView>(R.id.titleArea)

            imageArea.setImageResource(items.image)
            amountArea.text = "최소주문 ${items.amount}"
            titleArea.text = items.title

            // SpannableStringBuilder 타입으로 변환
            val spannable = SpannableStringBuilder(amountArea.text.toString())
            // 인덱스(0~3)에 해당 되는 텍스트에 회색 적용
            spannable.setSpan(
                ForegroundColorSpan(Color.GRAY),
                0,
                4,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            // TextView builder 적용
            amountArea.text = spannable

        }
    }

}

👩🏻‍💻 Swiperefreshlayout에 OnRefreshListener 등록하기

💡 binding.refreshLayout.isRefreshing = false
refresh 작업이 완료 되었을 경우 isRefreshing을 false로 변경해줘야한다.
변경해주지 않을 경우 새로고침 progress bar가 계속 표시되며 새로고침이 불가능해진다.

  • CardViewActivity.kt
class CardViewActivity : AppCompatActivity() {
    private lateinit var binding: ActivityCardViewBinding
    private val itemList = mutableListOf<CardModel>()
    private lateinit var cardViewAdapter: CardviewAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_card_view)
		
        // 리스트에 CardModel 형식으로 데이터를 넣어준다.
        itemList.add(CardModel("솔솥밥", "21,000원", R.drawable.cv_food_01))
        itemList.add(CardModel("사생활", "18,000원", R.drawable.cv_food_02))
        itemList.add(CardModel("행운동 조개", "20,000원", R.drawable.cv_food_03))
        itemList.add(CardModel("부촌 육회", "19,000원", R.drawable.cv_food_04))
        itemList.add(CardModel("시금치 통닭", "18,000원", R.drawable.cv_food_05))

        cardViewAdapter = CardviewAdapter(itemList)
        // recyclerview의 adapter에 CardViewAdapter를 설정한다.
        binding.recyclerview.adapter = cardViewAdapter
        // recyclerview에 layoutmanager를 설정한다.
        binding.recyclerview.layoutManager = LinearLayoutManager(this)
 
        onRefresh()
    }

    private fun onRefresh() {
    	// Swiperefreshlayoutdp OnRefreshListener를 등록한다.
        binding.refreshLayout.setOnRefreshListener {
        	// 새로고침 될 때 리스트의 요소들을 랜덤하게 재배열한다.
            itemList.shuffle()
            // adapter에 데이터가 변경 되었음을 알린다.
            cardViewAdapter.notifyDataSetChanged()
            // isRefreshing = false 인 경우 새로고침 완료시 새로고침 아이콘이 사라진다.
            binding.refreshLayout.isRefreshing = false
        }
    }
}
profile
개발 공부 기록 🌱

0개의 댓글