如何使用 Kotlin 正确突出显示 Android RecyclerView 中选中的项目?
此示例演示了如何使用 Kotlin 正确突出显示 Android RecyclerView 中选中的项目。
步骤 1 − 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml 中。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://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="http://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="http://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="http://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 中
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://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 Studio 运行应用程序,请打开项目中的一个 activity 文件,然后点击工具栏中的运行 图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕
广告