Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 Android RecyclerView 선택 항목 강조 표시하기 – 단계별 완벽 가이드

개요

Kotlin을 사용하면 Android RecyclerView에서 사용자가 탭한 항목을 시각적으로 강조 표시하는 기능을 비교적 간단하게 구현할 수 있습니다. 이 글에서는 SparseBooleanArray로 항목별 선택 상태를 추적하고, selector(StateListDrawable)를 배경으로 지정해 선택된 항목의 색상을 자동으로 변경하는 방법을 단계별로 알아보겠습니다.

완성하면 리스트 항목을 한 번 탭했을 때 해당 항목이 초록색으로 강조되고, 다시 탭하면 선택이 해제되는 멀티 선택 방식의 리스트를 만들 수 있습니다.

1단계 — 새 프로젝트 만들기

Android Studio에서 File → New Project로 이동한 후, 새 프로젝트 생성에 필요한 정보를 모두 입력해 빈 프로젝트를 만듭니다.

2단계 — 메인 레이아웃 작성 (activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 전체를 채우는 RecyclerView 하나만 배치하는 단순한 구조입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp"
   tools:context=".MainActivity">
   <androidx.recyclerview.widget.RecyclerView
      android:id="@+id/recyclerView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:paddingBottom="8dp" />
</RelativeLayout>

3단계 — 메인 액티비티 작성 (MainActivity.kt)

src/MainActivity.kt에 다음 코드를 추가합니다. RecyclerView에 LayoutManager와 어댑터를 연결하고, 항목 사이에 구분선을 그려 주는 ItemDecoration도 함께 등록합니다.

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
      recyclerView.addItemDecoration(SimpleItemDecoration(this))
      val layoutManager = LinearLayoutManager(this@MainActivity)
      recyclerView.layoutManager = layoutManager
      val posts = returnListItems()
      val adapter = RecyclerViewAdapter(this@MainActivity, posts)
      recyclerView.adapter = adapter
   }
   private fun returnListItems(): List<ItemObject>? {
      val items: MutableList<ItemObject> = ArrayList()
      items.add(ItemObject("Ballon'd'or", "2007", "Ricardo KaKa"))
      items.add(ItemObject("Ballon'd'or", "2008", "Cristiano Ronaldo"))
      items.add(ItemObject("Ballon'd'or", "2009 - 2012, 2015", "Lionel Messi"))
      items.add(ItemObject("Ballon'd'or", "2013, 2014, 2016, 2017", "Cristiano Ronaldo"))
      items.add(ItemObject("Ballon'd'or", "2018", "Luca Modric"))
      items.add(ItemObject("Ballon'd'or", "2019", "Lionel Messi"))
      return items
   }
}

예제 데이터는 축구 발롱도르(Ballon d'Or) 수상 기록을 활용했습니다. 수상 연도와 선수 이름이 담긴 리스트를 반환하는 returnListItems() 함수를 참고하세요.

4단계 — 코틀린 클래스 파일 추가

아래 네 개의 클래스 파일을 생성하고 각각의 코드를 입력합니다.

ItemObject.kt

리스트에 표시할 데이터 모델입니다. 수상명, 수상 연도, 선수 이름 세 개의 문자열 필드를 가집니다.

internal class ItemObject(val awardTitle: String, val awardYear: String, val player: String) {
}

RecyclerViewAdapter.kt

RecyclerView 어댑터입니다. 각 위치의 데이터를 뷰홀더에 바인딩하고, 전체 항목 개수를 반환합니다.

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView
class RecyclerViewAdapter internal constructor(
   context: MainActivity,
   private val itemList: List<ItemObject>?
) : RecyclerView.Adapter<RecyclerViewHolders>() {
   @NonNull
   override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolders {
      val layoutView = LayoutInflater.from(parent.context).inflate(R.layout.list_layout, null)
      return RecyclerViewHolders(layoutView)
   }
   override fun onBindViewHolder(holder: RecyclerViewHolders, position: Int) {
      holder.awardTitle.text = "Award Title: " + itemList!![position].awardTitle
      holder.awardYear.text = "Award Year: " + itemList[position].awardYear
      holder.player.text = "Player Name: " + itemList[position].player
   }
   override fun getItemCount(): Int {
      return this.itemList!!.size
   }
}

RecyclerViewHolders.kt

이 예제의 핵심 부분입니다. ViewHolder 내부에 SparseBooleanArray를 두어 항목별 선택 여부를 저장하고, 클릭 이벤트가 발생하면 해당 위치의 값을 토글(toggle)한 뒤 view.isSelected를 갱신합니다. 뷰의 selected 상태가 바뀌면 배경으로 지정된 selector 드로어블이 자동으로 반응해 배경색이 전환됩니다.

import android.util.SparseBooleanArray
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
class RecyclerViewHolders(itemView: View) : ViewHolder(itemView),
View.OnClickListener {
   var awardTitle: TextView
   var awardYear: TextView
   var player: TextView
   private val selectedItems = SparseBooleanArray()
   override fun onClick(view: View) {
      if (selectedItems[adapterPosition, false]) {
         selectedItems.delete(adapterPosition)
         view.isSelected = false
      }
      else {
         selectedItems.put(adapterPosition, true)
         view.isSelected = true
      }
   }
   init {
      itemView.setOnClickListener(this)
      awardTitle = itemView.findViewById(R.id.awardTitle)
      awardYear = itemView.findViewById(R.id.awardYear)
      player = itemView.findViewById(R.id.playerName)
   }
}

SimpleItemDecoration.kt

리스트 항목 사이에 구분선을 그려 주는 RecyclerView.ItemDecoration 구현체입니다.

import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import androidx.annotation.NonNull
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
internal class SimpleItemDecoration(context: Context) : RecyclerView.ItemDecoration() {
   private val drawable: Drawable = ContextCompat.getDrawable(context, R.drawable.line_divider)!!
   override fun onDrawOver(
      @NonNull canvas: Canvas,
      parent: RecyclerView,
      @NonNull state: RecyclerView.State
   )
   {
      val left = parent.paddingLeft
      val right = parent.width - parent.paddingRight
      val childCount = parent.childCount
      for (i in 0 until childCount) {
         val child = parent.getChildAt(i)
         val params = child.layoutParams as RecyclerView.LayoutParams
         val top = child.bottom + params.bottomMargin
         val bottom = top + drawable.intrinsicHeight
         drawable.setBounds(left, top, right, bottom)
         drawable.draw(canvas)
      }
   }
}

5단계 — Drawable 리소스 파일 추가

아래 두 개의 drawable 리소스 파일을 생성하고 코드를 입력합니다.

background_selector.xml

선택 상태에 따라 배경색을 바꿔 주는 selector입니다. 항목이 선택되면 밝은 초록색(holo_green_light), 선택되지 않으면 보라색(holo_purple)이 적용됩니다.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
   <item android:drawable="@android:color/holo_green_light" android:state_pressed="false" android:state_selected="true" />
   <item android:drawable="@android:color/holo_purple" android:state_selected="false" />
</selector>

line_divider.xml

항목 사이에 그릴 2dp 높이의 구분선 shape 리소스입니다.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
   android:shape="rectangle">
   <size
      android:width="2dp"
      android:height="2dp" />
   <solid android:color="@color/colorPrimaryDark" />
</shape>

6단계 — 항목 레이아웃 작성 (list_layout.xml)

리스트의 각 항목에 표시될 레이아웃입니다. 컨테이너의 android:background 속성을 위에서 만든 @drawable/background_selector로 지정하는 것이 선택 강조 기능의 핵심입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:id="@+id/container"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@drawable/background_selector"
   android:padding="16dp">
   <TextView
      android:id="@+id/awardTitle"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dp"
      android:text="New Text"
      android:textColor="@android:color/background_dark"
      android:textSize="18sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/awardYear"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/awardTitle"
      android:layout_alignStart="@+id/awardTitle"
      android:layout_marginTop="20dp"
      android:text="New Text"
      android:textColor="@android:color/background_dark" />
   <TextView
      android:layout_marginBottom="10dp"
      android:id="@+id/playerName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentEnd="true"
      android:text="New Text"
      android:textColor="@android:color/background_dark" />
</RelativeLayout>

7단계 — AndroidManifest.xml 수정

매니페스트 파일에 아래와 같이 MainActivity를 등록합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
   package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

앱 실행하기

실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정하고 진행하겠습니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) Kotlin으로 Android RecyclerView 선택 항목 강조 표시하기 – 단계별 완벽 가이드 아이콘을 클릭합니다. 옵션 목록에서 본인의 모바일 기기를 선택하면, 기기에 앱이 실행되고 기본 화면이 표시됩니다.

Kotlin으로 Android RecyclerView 선택 항목 강조 표시하기 – 단계별 완벽 가이드

Kotlin으로 Android RecyclerView 선택 항목 강조 표시하기 – 단계별 완벽 가이드

리스트의 항목을 탭하면 해당 항목이 초록색으로 강조 표시되고, 다시 탭하면 원래 색상으로 돌아오는 것을 확인할 수 있습니다. SparseBooleanArray를 활용했기 때문에 여러 항목을 동시에 선택하는 것도 가능합니다.