Android Jetpack

Android View에 대한 접근 - 5 (Adapter ViewBinding)

----___<<<<< 2022. 3. 9. 16:24

 

 Adapter에서 ViewBinding을 이용해서 View에 접근하는 방법입니다.

 

 아래의 예제를 활용해서 Adapter부분만 ViewBinding으로 변경해보겠습니다.

 

https://philosopher-chan.tistory.com/1517

 

RecyclerView Example

 간단한 RecyclerView 예제입니다.

philosopher-chan.tistory.com

 

 Adapter를 아래와 같이 변경하면 됩니다.

 

class CustomAdapter(private val dataSet: ArrayList<String>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
class ViewHolder(binding : TextRowItemBinding) : RecyclerView.ViewHolder(binding.root) {
val textView = binding.textView
}
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
val view = TextRowItemBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)
return ViewHolder(view)
}
// Replace the contents of a view (invoked by the layout manager)
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
// Get element from your dataset at this position and replace the
// contents of the view with that element
viewHolder.textView.text = dataSet[position]
}
// Return the size of your dataset (invoked by the layout manager)
override fun getItemCount() = dataSet.size
}