recyclerview点击后改变item颜色
时间: 2023-07-05 18:29:14 浏览: 57
要实现RecyclerView点击后改变item的颜色,可以在RecyclerView的Adapter中设置点击事件,在点击事件中改变item的颜色。具体实现步骤如下:
1. 在item的布局文件中,设置一个根布局,并将需要改变颜色的子视图放在该布局中。例如,以下是一个item的布局文件:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<TextView
android:id="@+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item" />
</LinearLayout>
```
在该布局中,将TextView放在LinearLayout中,LinearLayout作为根布局。
2. 在RecyclerView的Adapter中,设置点击事件。在ViewHolder的构造函数中,获取item的根布局,并设置点击事件。例如,以下是一个RecyclerView的Adapter的代码:
```kotlin
class MyAdapter(private val itemList: List<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(itemList[position])
}
override fun getItemCount(): Int {
return itemList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val itemLayout: LinearLayout = itemView.findViewById(R.id.item_layout)
private val itemText: TextView = itemView.findViewById(R.id.item_text)
init {
itemLayout.setOnClickListener {
val pos = adapterPosition
if (pos != RecyclerView.NO_POSITION) {
itemLayout.setBackgroundColor(ContextCompat.getColor(itemView.context, R.color.colorAccent))
itemText.setTextColor(ContextCompat.getColor(itemView.context, R.color.white))
}
}
}
fun bind(item: String) {
itemText.text = item
}
}
}
```
在ViewHolder中获取item的根布局和需要改变颜色的子视图。在根布局上设置点击事件,获取item的位置,然后通过`itemLayout.setBackgroundColor()`和`itemText.setTextColor()`方法改变item的颜色和TextView的颜色。注意,在获取颜色时需要使用`ContextCompat.getColor()`方法,这样可以兼容不同版本的Android系统。
这样,当用户点击item时,item的背景颜色和TextView的文本颜色就会改变。