Sunday, February 4, 2018

android kotlin - RecyclerView example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get the context
        context = this

        // Get the widgets reference from XML layout
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)

        // initialize a mutable list of users
        val users = mutableListOf(
            User("Jenny","Jones","USA"),
            User("Robin","Jackman","UK"),
            User("Suhailah","Alam","France"),
            User("Hasiba","Yeasmin","Germany"),
            User("Taylor","Edward","India"),
            User("Vivian","Dickens","Finland"),
            User("Eliza","Clifford","Romania"),
            User("Melinda","Newman","Uganda"),
            User("Harley","Gilbert","Romania")
        )

        // initialize a new linear layout manager
        val linearLayoutManager = LinearLayoutManager(
            context, // context
            RecyclerView.VERTICAL, // orientation
            false // reverse layout
        )

        // specify the layout manager for recycler view
        recyclerView.layoutManager = linearLayoutManager

        // finally, data bind the recycler view with adapter
        recyclerView.adapter = RecyclerViewAdapter(users)
    }
}


// create user data class
data class User(var firstName:String,
    var lastName:String,var location:String)
RecyclerViewAdapter.kt

package com.cfsuman.kotlintutorials

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView


class RecyclerViewAdapter(private val users: MutableList<User>)
    : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup, viewType: Int): ViewHolder {
        // inflate the custom view from xml layout file
        val view: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.custom_view,parent,false)

        // return the view holder
        return ViewHolder(view)
    }


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // display the current user full name and location
        users[position].apply {
            holder.name.text = "$firstName $lastName"
            holder.location.text = location
        }
    }


    override fun getItemCount(): Int {
        // returns the total number of items in
        // the data set held by the adapter.
        return users.size
    }


    class ViewHolder(itemView: View)
        : RecyclerView.ViewHolder(itemView){
        val name: TextView = itemView.findViewById(R.id.tvName)
        val location: TextView = itemView.findViewById(R.id.tvLocation)
    }


    // this two methods useful for avoiding duplicate item
    override fun getItemId(position: Int): Long {
        return position.toLong()
    }


    override fun getItemViewType(position: Int): Int {
        return position
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#F0FFFF">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
custom_view.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#F0F8FF"
    app:cardCornerRadius="8dp"
    app:cardElevation="5dp"
    app:cardMaxElevation="7dp"
    app:contentPadding="24dp"
    android:layout_margin="4dp" >

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/tvName"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:fontFamily="sans-serif-condensed-medium"
            tools:text="Jenny Jones"
            android:textColor="#003153"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tvLocation"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            tools:text="India"
            android:textSize="18sp"
            android:fontFamily="sans-serif-condensed-medium"
            android:layout_marginTop="8dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/tvName" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>