RecyclerView를 쓰다보면,

누른 item에만 효과를 주고 싶을때가 있다.

 

나같은 경우에는 결과 item의 개수에 따라 유동적으로 버튼이 생성되게 구현했는데,

누른 버튼만 빨간색으로 바뀌고, 나머지 버튼들은 검은색으로 설정하게 했다.

 

결과 미리보기

 

소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
inner class Holder(itemView: View?, itemClick: (RecyclerItem) -> Unit) : RecyclerView.ViewHolder(itemView!!) {
        val listItem : ConstraintLayout? = itemView?.findViewById(R.id.mlistItem)
        val title = itemView?.findViewById<TextView>(R.id.mTitle)
        val value = itemView?.findViewById<TextView>(R.id.mValue)
 
        fun bind (item : RecyclerItem, context: Context) {
            title?.text = item.mItem
            value?.text = item.mValue
            itemView.setOnClickListener {
                itemClick(item)
                row_index = position
                notifyDataSetChanged()
            }
        }
}
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
override fun onBindViewHolder(holder: Holder, position: Int) {
        holder?.bind(valueList[position], context)
        if(row_index == position) {
            holder.listItem?.setBackgroundResource(R.drawable.custom_ripple_unchecked)
            holder.title?.setTextColor(ContextCompat.getColor(context, R.color.colorRed))
            holder.value?.setTextColor(ContextCompat.getColor(context, R.color.colorRed))
        }
        else {
            holder.listItem?.setBackgroundResource(R.drawable.custom_ripple)
            holder.title?.setTextColor(ContextCompat.getColor(context, R.color.colorBlack))
            holder.value?.setTextColor(ContextCompat.getColor(context, R.color.colorBlack))
        }
}
cs

 

bind에서 onclick하는 경우 해당 item의 position을 저장하고,

 

onBindViewHolder에서 조건문으로 위치가 일치하면,

setBackgroundResoure 해주고 일치하지 않으면 검은색으로 바꾼다.

+ Recent posts