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 해주고 일치하지 않으면 검은색으로 바꾼다.
'개발 > 안드로이드' 카테고리의 다른 글
[Kotlin] 안드로이드 전역변수 선언하기 (0) | 2021.04.30 |
---|---|
[Kotlin] 안드로이드 다른 class에서 UI 그리기 (0) | 2020.10.16 |
[Kotlin] 안드로이드 bitmap으로부터 uri가져온 뒤, filepath 찾기 (3) | 2020.10.14 |
[Kotlin] 안드로이드 스튜디오 카메라 회전 및 화질 향상 (0) | 2020.10.14 |
[Kotlin] 안드로이드 카메라 구현 예제 (0) | 2020.10.14 |