RecyclerView sử dụng Kotlin sẽ code như thế nào ?

1. RecyclerView là gì?

RecyclerView là một View mới trong android giống như ListView nhưng mạnh mẽ hơn rất nhiều.
RecyclerView cho phép chúng ta load dữ liệu nhiều hơn ListView, vuốt mượt hơn, hiệu ứng đẹp hơn và hỗ trợ đa dạng layout của các phần tử trong danh sách.

Sử dụng RecyclerView trong android JAVA Các bạn xem ở đây.

2. Sử dụng RecyclerView  với Kotlin.

Tương tự như code bằng Java, code bằng Kotlin cũng rất đơn giản và ngắn gọn.

1: Môi trường:
–  Android Studio : 3.0.1

2: Mở build.gradle import thư viện

implementation 'com.android.support:recyclerview-v7:26.1.0'

3: Tạo giao diện XML

  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rcv_month"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp" />
</RelativeLayout>
  • item_month.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <TextView
        android:id="@+id/tv_month_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20dp"
        tools:text="Tháng 10" />
</RelativeLayout>

4. Tạo file MonthHolder.java

/**
 * Created by NguyenLinh on 3/18/2018.
 * Web: www.androdcoban.com
 */
class MonthHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
    var tvMonthName: TextView = itemView!!.findViewById(R.id.tv_month_name)
}

5. Tạo adapter để đẩy dữ liệu lên  MonthAdapter.java

Các bạn có thể dùng cách khác để viết constructor, tuy nhiên mình dùng kiểu này cho nó giống với java để dễ nhìn.

/**
 * Created by NguyenLinh on 3/18/2018.
 * Web: www.androdcoban.com
 */
class MonthAdapter : RecyclerView.Adapter<MonthHolder> {
    private var arrMonthName: ArrayList<String>

    constructor(arrMonthName: ArrayList<String>) : super() {
        this.arrMonthName = arrMonthName
    }

    override fun onBindViewHolder(holder: MonthHolder?, position: Int) {
        if (holder != null) {
            holder.tvMonthName.text = arrMonthName[position]
        }
    }

    override fun getItemCount(): Int {
        return arrMonthName.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MonthHolder {
        return MonthHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_month, parent, false))
    }

}

5. Tạo dữ liệu setup adapter tại MainActivity

class MainActivity : AppCompatActivity() {
    private lateinit var arrMonthName: ArrayList<String>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        arrMonthName = ArrayList()
        for (i in 0 until 12) {
            arrMonthName.add("Tháng " + (i + 1).toString())
        }
        rcv_month.layoutManager = LinearLayoutManager(this)
        rcv_month.setHasFixedSize(true)
        rcv_month.itemAnimator = DefaultItemAnimator()
        rcv_month.addItemDecoration(DividerItemDecoration(rcv_month.context, DividerItemDecoration.VERTICAL))
        rcv_month.adapter = MonthAdapter(arrMonthName)
    }
}

6. Bonus

  • Để tạo hiệu ứng ripple khi click vào item trên RecyclerView các bạn thêm dòng này vào item_month.xml
  android:background="?attr/selectableItemBackground"
  • Để set sự kiện OnClick các bạn mở Adapter sửa phần onBindViewHolder như sau:
  override fun onBindViewHolder(holder: MonthHolder?, position: Int) {
        if (holder != null) {
            holder.tvMonthName.text = arrMonthName[position]
            holder.itemView.setOnClickListener {
                Log.d("Click Item:",arrMonthName[position])
            }
        }
    }

Vậy là đã xong tiến hành Run project, Chúc các bạn thành công!

Nguyễn Linh

Chia sẻ để cùng tiến bộ...