와챠의 우당탕탕 코딩 일기장

[Android/Kotlin]Changing background color of selected only one item in recyclerview/RecyclerView 선택된 item 1개만 배경색 바꾸기 본문

코딩 일기장/Android(Kotlin)

[Android/Kotlin]Changing background color of selected only one item in recyclerview/RecyclerView 선택된 item 1개만 배경색 바꾸기

minWachya 2022. 7. 28. 19:55
반응형

아래 사진과 같이 선택한 하나의 item 배경색만 바꿔보려고 한다.!!

생각보다 넘 간단해서 깜놀


item_building.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewModel"
            type="com.example.safetymanagement2022.ui.list_building.ListBuildingViewModel" />

        <variable
            name="building"
            type="com.example.safetymanagement2022.model.Building" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginVertical="5dp"
        android:background="@drawable/background_gradient_r15"
        android:onClick="@{() -> viewModel.openBuildingDetail(building.buildingId)}">

        <ImageView
            android:id="@+id/iv_building"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_marginStart="28dp"
            android:layout_marginTop="20dp"
            android:contentDescription="@string/description_icon_building"
            android:src="@drawable/ic_building"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tv_building_name"
            style="@style/TextMedium.16.bold"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="14dp"
            android:layout_marginEnd="28dp"
            android:maxLines="1"
            android:text="@{building.name}"
            app:layout_constraintBottom_toBottomOf="@id/iv_building"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/iv_building"
            app:layout_constraintTop_toTopOf="@id/iv_building"
            tools:text="건물1" />

        <TextView
            android:id="@+id/tv_building_context"
            style="@style/TextMedium"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:layout_marginEnd="28dp"
            android:layout_marginBottom="20dp"
            android:maxLines="1"
            android:text="@{building.context}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="@id/tv_building_name"
            app:layout_constraintTop_toBottomOf="@id/tv_building_name"
            tools:text="어쩌구어쩌구어쩌구" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

 

Adapter부분이다

// 주석된 부분만 보면 됨!! 간단하죠

class ConnectBuildingAdapter: ListAdapter<ConnectBuilding, ConnectBuildingAdapter.ConnectBuildingViewHolder>(
    ListBuildingDiffCallback()) {
    private lateinit var binding: ItemDialogBuildingBinding
    private var selectedBuildingId: String = ""

	// 선택한 view
    private var currView: TextView? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConnectBuildingViewHolder {
        binding = ItemDialogBuildingBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ConnectBuildingViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ConnectBuildingViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class ConnectBuildingViewHolder(private val binding: ItemDialogBuildingBinding): RecyclerView.ViewHolder(binding.root) {
        fun bind(building: ConnectBuilding) {
            binding.building = building
            binding.executePendingBindings()

            binding.tvBuildingName.setOnClickListener {
                selectedBuildingId = building.buildingId

				// 선택한 view가 없을 때
                if(currView == null) {
                	// currView 초기화 + 배경색 오렌지 색으로 지정
                    currView = binding.tvBuildingName
                    currView?.setBackgroundColor(Color.parseColor("#FFC589"))
                } else {
                	// 선택한 view가 있을 때
                    // 기존 선택된 view 배경색 흰 색으로 변경
                    currView?.setBackgroundColor(Color.parseColor("#FFFFFF"))
                    // currView 갱신 + 배경색 오렌지 색으로 변경
                    currView = binding.tvBuildingName
                    currView?.setBackgroundColor(Color.parseColor("#FFC589"))
                }
            }
        }
    }

    fun getBuildingId(): String = selectedBuildingId
}

class ListBuildingDiffCallback: DiffUtil.ItemCallback<ConnectBuilding>() {
    override fun areItemsTheSame(oldItem: ConnectBuilding, newItem: ConnectBuilding): Boolean {
        return oldItem.buildingId == newItem.buildingId
    }
    override fun areContentsTheSame(oldItem: ConnectBuilding, newItem: ConnectBuilding): Boolean {
        return oldItem == newItem
    }
}

 

... 큰 설명이 필요 없겟죠

반응형
Comments