Skip to content

Instantly share code, notes, and snippets.

@SurajBahadur
Created January 29, 2021 10:32
Show Gist options
  • Save SurajBahadur/ce5d27c16e9d64e7f38875577eb4c34c to your computer and use it in GitHub Desktop.
Save SurajBahadur/ce5d27c16e9d64e7f38875577eb4c34c to your computer and use it in GitHub Desktop.
Refracting RecyclerView Adapter to DataBinding
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/app_bg"
tools:context=".activity.stats.StatsActivity">
<include
android:id="@+id/toolbarView"
layout="@layout/toolbar_custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvStats"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/toolbarView"
tools:itemCount="1"
tools:listitem="@layout/stats_overall_adapter">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
class StatsOverallAdapter(val data: Data?) : RecyclerView.Adapter<StatsOverallAdapter.StatsOverallViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StatsOverallViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = StatsOverallAdapterBinding.inflate(inflater,parent,false)
return StatsOverallViewHolder(binding)
}
override fun getItemCount() = 1
override fun onBindViewHolder(holder: StatsOverallViewHolder, position: Int) = holder.bind(data)
class StatsOverallViewHolder(val binding: StatsOverallAdapterBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(data: Data?) {
with(binding) {
//access your views here
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment