MainActivity.kt
package com.example.jetpack
import android.os.Bundle
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// list of plants to populate grid view
val list = listOf(
"Striped alder",
"Amy root",
"Arizona sycamore",
"Green ash",
"Cherry birch",
"Gray birch",
"Mahogany birch",
"Spice birch",
"Yellow birch"
)
// array adapter for grid view
ArrayAdapter(this,android.R.layout.simple_list_item_1,list).apply {
gridView.adapter = this
}
// set grid view item click listener
gridView.setOnItemClickListener { adapterView, view, i, l ->
// get grid view clicked item text
val selectedItem = adapterView.getItemAtPosition(i).toString()
textView.text = selectedItem
}
}
}
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:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#EDEAE0">
<GridView
android:id="@+id/gridView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="#F3F0E7"
android:numColumns="2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textSize="30sp"
android:textColor="#00356B"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/gridView"
tools:text="TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
- android kotlin - Get battery temperature programmatically
- android kotlin - Repeat a task periodically
- android kotlin - Do a task after a delay
- android kotlin - Get app first install time
- android kotlin - Get app version name and code
- android kotlin - Detect screen orientation change
- android kotlin - Get screen orientation programmatically
- android kotlin - Convert dp to pixels programmatically
- android kotlin - Get screen size from context
- android kotlin - RecyclerView horizontal
- android kotlin - RecyclerView divider line
- android kotlin - GridView item height
- android kotlin - GridView add item dynamically
- android kotlin - GridView selected item background color
- android kotlin - Border/divider between GridView items