em kotlin: uma recyclerView

ficheiro: MainActivity.kt

package pt.deis.estuda.estudoslistview2

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun onRecyclerView(view: View) {
        val intent = Intent(this,RecyclerViewActivity::class.java)
        startActivity(intent)
    }
}

ficheiro: 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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:onClick="onRecyclerView"
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:text="recycler view"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

ficheiro: activity_recycler_view.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardCornerRadius="6dp"
    app:cardElevation="6dp"
    android:layout_margin="6dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:textStyle="bold"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:id="@+id/recyclerTV1"
            android:textSize="24sp"
            android:text="Text 1" />
        <TextView
            android:background="#f0f0f0"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:id="@+id/recyclerTV2"
            android:textSize="20sp"
            android:text="Text 2" />
        <TextView
            android:background="#808080"
            android:textColor="#ffffff"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:id="@+id/recyclerTV3"
            android:textSize="16sp"
            android:text="Text 3" />
    </LinearLayout>
</androidx.cardview.widget.CardView>

ficheiro: 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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RecyclerViewActivity"
    android:padding="16dp">

    <androidx.recyclerview.widget.RecyclerView
        android:padding="4dp"
        android:id="@+id/recyclerviewList"
        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>

ficheiro: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pt.deis.estdua.arecyclerview">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ARecyclerView">

        <activity
            android:name=".RecyclerViewActivity"
            android:label="ListView"
            android:parentActivityName=".MainActivity" />


        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

ficheiro: RecyclerViewActivity.kt

package pt.deis.estuda.arecyclerview

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import kotlinx.android.synthetic.main.activity_recycler_view.*
import kotlin.random.Random

class RecyclerViewActivity : AppCompatActivity() {
    data class Dados(val str1:String,val str2 : String, val str3:String)
    val data = arrayListOf<Dados>()

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

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.subtitle = "Exemplo Recycler View"

        //sorterar numeros aleatoriamente
        repeat(Random.nextInt(10,20)) {
            val item = Dados("Titulo ${Random.nextInt(0,1000)}",getStr(50,400),getStr(5,20))
            data.add(item)
        }

        //atribuir um layoutManager, um gestor para organizar os objectos, existem assim 3 tipos
        //LinearLayoutManager ou GridLayoutManager ou StaggeredGridLayoutManager
        //LinearLayoutManager.VERTICA - > lista com scroll na vertical
        //recyclerviewList.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
        //recyclerviewList.layoutManager = GridLayoutManager(this,2,GridLayoutManager.VERTICAL,false)
        recyclerviewList.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        //MyRVAdapter derivado do RecyclerView.Adapter
        recyclerviewList.adapter = MyRVAdapter(data)

    }

    fun getStr(minc:Int,maxc: Int) : String {
        var str = ""
        val nrc = Random.nextInt(minc,maxc)
        repeat(nrc) {
            str += Random.nextInt(65,90).toChar()
        }
        return str
    }

    //é obrigatório o objecto ViewHolder, que representa cada um dos itens que vai ser visualizado
    class MyRVAdapter(val data : ArrayList<Dados>) : RecyclerView.Adapter<MyRVAdapter.MyViewHolder>() {
        class MyViewHolder(view : View) : RecyclerView.ViewHolder(view) {
            var tv1 : TextView = view.findViewById(R.id.recyclerTV1)
            var tv2 : TextView = view.findViewById(R.id.recyclerTV2)
            var tv3 : TextView = view.findViewById(R.id.recyclerTV3)

            //não é necessário.. e o update vai ser chamado pelo onBindViewHolder
            fun update(str1:String,str2:String,str3:String) {
                tv1.text = str1
                tv2.text = str2
                tv3.text = str3
            }
        }

        //criar as vistas
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.recyclerview_item ,parent,false)
            //e é retornado no contexto do MyViewHolder
            return MyViewHolder(view)
        }
//inflate de um layout
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            holder.update(data[position].str1,data[position].str2,data[position].str3)
        }
//método para saber quantos elementos tem a lista
        override fun getItemCount(): Int = data.size
    }

}

ficheiro: build.gralde (Module)

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions' // obrigatorio para aceder aos diferentes layouts sem usar o findId
}
...

Tags : , , , , ,

0 thoughts on “em kotlin: uma recyclerView”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.