Here is the easiest way to bind adapter to recycler view with few lines of code using Last Adapter. Don’t write recycler view adapter again. Not even viewHolder!.
Basically Last Adapter use Data Binding to bind data with your views.
Data Binding Library is a support library that enables you to bind UI elements in your layouts to data sources in your app using a declarative style rather than programmatically.
Enable Data Binding in the project by adding below lines in your app level build.gradle file,
// apply plugin: 'kotlin-kapt' // this line only for Kotlin projects android { ... dataBinding.enabled true }
Then, add dependency for Last Adapter,
dependencies { implementation 'com.github.nitrico.lastadapter:lastadapter:2.3.0' }
Usage :
Create your item layout with <layout> as root.
Here, ProjectDetails is Model class, which type of item you want to display into recycler view.
<layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="details" type="com.example.android.ProjectDetails"/> </data> <TextView id="@+id/tv_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{details.name}"/> </layout>
You can convert your existing layout into data binding layout by clicking Alt+Enter like below,
Now, set your data into an adapter,
It is important for all the item types to have the same variable name, in this case “details“. This name is passed to the adapter builder as BR.variableName, in this case, it is BR.details:
// Java new LastAdapter(listOfItems, BR.details) .map(ProjectHeader.class, R.layout.item_header) .map(ProjectDetails.class, R.layout.item_details) .into(recyclerView);
// Kotlin LastAdapter(listOfItems, BR.details) .map<ProjectHeader>(R.layout.item_header) .map<ProjectDetails>(R.layout.item_details) .into(recyclerView)
Note : If you are facing any issue after adding BR.variableName, rebuild your project. Because sometimes Binding files are not generating (Here it will be ItemHeaderBinding or ItemDetailsBinding) and giving compile time error.
You can use ObservableList,
if you want automatically notify your adapter when data changed, else use List.
You can get click listener like below in same activity/fragment,
// Kotlin LastAdapter(listOfItems, BR.item) .map<Header>(R.layout.item_header){ onBind{ it-> //to something with your item views and data val textViewTitle = it.binding.tvTitle textViewTitle.text = it.binding.details.name //here "details" is your variable, which you have taken in xml in data tag }l̥ onClick{ //redirect on next screen on click of list item } .map<Point>(R.layout.item_point) .into(recyclerView)