Wednesday, October 2, 2019

android kotlin - ArrayList example

MainActivity.kt

package com.example.jetpack

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        btn.setOnClickListener {
            val list = arrayListOf<String>("Red","Green","Blue")
            list.add("Black")
            list.add(1,"Magenta")

            textView.text = "arrayListOf<String>()"
            list.forEach{
                textView.append("\n$it")
            }

            val list2 = ArrayList<String>()
            list2.add("Red")
            list2.add("Green")
            list2.add("Yellow")

            textView.append("\n\nArrayList<String>()")
            list2.forEach{
                textView.append("\n$it")
            }

            val list3 = arrayListOf<Any>("Red",1,2,"Green",6)
            textView.append("\n\nNew List: Any")
            list3.forEach{
                textView.append("\n${it.toString()}")
            }
        }
    }
}
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">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Hello World!"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn" />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Generate ArrayList"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
More android examples