이 예는 Kotlin을 사용하여 Android RecyclerView에서 선택한 항목을 올바르게 강조 표시하는 방법을 보여줍니다.
1단계 − Android Studio에서 새 프로젝트를 생성하고 파일 ⇒ 새 프로젝트로 이동하여 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.
2단계 − res/layout/activity_main.xml에 다음 코드를 추가합니다.
<?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단계 − src/MainActivity.kt에 다음 코드 추가
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 } }
4단계 − 아래와 같이 kotlin 클래스 파일을 생성하고 해당 코드를 추가
ItemObject.kt -
internal class ItemObject(val awardTitle: String, val awardYear: String, val player: String) { }
RecyclerViewAdapter.kt -
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 -
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 -
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단계 − 아래와 같이 드로어블 리소스 파일을 생성하고 해당 코드를 추가합니다.
background_selecter.xml
<?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
<?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)을 생성하고 다음 코드를 추가합니다.
<?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.xmlv
에 다음 코드 추가<?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 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 실행을 클릭합니다. 툴바에서 아이콘. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오.