Overview
Recycler View
RecyclerView is a boon to Android developers when it comes to handling a huge amount of data in list form.
Topics
RecyclerView with Kotlin
We need to add compile com.android.support:recyclerview-v7:+ into our app-level gradle file
Then, we have to add recycler view in our xml file
<android.support.v7.widget.RecyclerView android:id="@+id/rv" android:layout_width="match_parent" android:layout_height="match_parent"/>
Now, create a row file with name row.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="45dp" /> </LinearLayout>
We have to create an adapter which will process the data and will display it in recycler view.
class MyAdapter(var names: ArrayList<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() { override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.title.text = names.get(position) } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder { var view = LayoutInflater.from(parent?.context).inflate(R.layout.row, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return names.size } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { var title: TextView = view.findViewById(R.id.tv) as TextView init { } } }
Finally, we have to set adapter to recycler view in main activity and also set the layout manager for recycler view.
rv = view?.findViewById(R.id.rv) as RecyclerView array.add("abc") array.add("def") array.add("ghi") array.add("jkl") array.add("mno") rv?.layoutManager = LinearLayoutManager(activity) rv?.adapter = MyAdapter(array)
Conclusion
Recycler view is a ‘must to know’ concept in recycler view. This solves many problems of list view. Hence, if you are new to android, get used to using it. This will help you in a lot of ways.