Como crear un RecyclerView en Android utilizando Kotlin

Como crear un RecyclerView en Android utilizando Kotlin

Android RecyclerView Kotlin Example

Hola amigos en esta ocasión vamos a crear un RecyclerView en Android utilizando Kotlin.

Como crear un proyecto en Android utilizando Kotlin(Aquí)

Vamos a crear un proyecto para desarrollar nuestro ejemplo y vamos a darle soporte a Kotlin para utilizar este lenguaje.

Diseño de RecyclerView en Android

Vamos a crear el diseño de nuestra aplicación y agregaremos el control RecyclerView.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

</android.support.constraint.ConstraintLayout>

El diseño quedara de la siguiente manera.

Ahora añadiremos un archivo xml y le pondremos list_layout.

<?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">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textViewGame"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="Belal Khan
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />

            <TextView
                android:id="@+id/textViewPlayer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="Ranchi, Jharkhand"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
        </LinearLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>

Diseño del row layout para nuestro RecyclerView.

Código de RecyclerView en Android utilizando Kotlin

Vamos a crear el código para nuestra aplicación y añadiremos dos clases una para los Games y otra que sera el adaptador.

Añadiremos la primera que sera Games.

data class Games(val NameGame: String, val NamePlayer: String)

Añadiremos el adaptador.

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView

/**
 * Created by Alejandro Dominguez on 7/15/2018.
 */

class CustomAdapter(val gameList: ArrayList<Games>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    //this method is returning the view for each item in the list
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.list_layout, parent, false)
        return ViewHolder(v)
    }

    //this method is binding the data on the list
    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        holder.bindItems(gameList[position])
    }

    //this method is giving the size of the list
    override fun getItemCount(): Int {
        return gameList.size
    }

    //the class is hodling the list view
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindItems(games: Games) {
            val textViewName = itemView.findViewById(R.id.textViewGame) as TextView
            val textViewPlayer  = itemView.findViewById(R.id.textViewPlayer) as TextView
            textViewName.text = games.NameGame
            textViewPlayer.text = games.NamePlayer
        }
    }
}

Y por ultimo al archivo MainActivity.

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.LinearLayout

class MainActivity : AppCompatActivity() {

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

        // Obtener referencia del objecto
        val recyclerView = findViewById(R.id.recyclerView) as RecyclerView

        // Agregar layoutManager
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)

        // Crear array list del User
        val games = ArrayList<Games>()

        // Añadir juegos y personajes
        games.add(Games("Resident Evil", "Leon S Kennedy"))
        games.add(Games("Silent Hill", "Pyramid Head"))
        games.add(Games("Outlast", "Miles Upshur"))
        games.add(Games("Amnesia", "Daniel"))

        // Crear adaptador
        val adapter = CustomAdapter(games)

        // Añadir recyclerView
        recyclerView.adapter = adapter
    }
}

Y con esto tendriamos listo nuestro ejemplo.

Como crear un emulador AVD en Android (Aquí)

Ahora vamos a crear un emulador AVD para ver nuestro ejemplo en ejecución.
Y con esto tendriamos listo nuestro RecyclerView utilizando Kotlin.

3 comentarios:

  1. Me ayudo de mucho a entender como funciona ReciclerView, soy nuevo en la programación de Apps con kotlin y de echo en el mundo Android, solo tengo 1 observación:

    en el adaptador:
    return RecyclerView.ViewHolder(v)
    lo cambie por
    return ViewHolder(v)

    Mil Gracias Godoy.

    ResponderEliminar
    Respuestas
    1. Me podrías ayudar ¿como le agrego un onClickListener?

      Eliminar
    2. Hola amigo disculpa la tardanza en responder, puedes revisar nuestro tutorial de Button y aplicar el OnClickListener de la misma forma para el RecyclerView al control que quieres que resiva el evento OnClick.
      Saludos.

      Eliminar