Android Kotlin: Changing GridView Selected Item Background Color
This code demonstrates how to customize the background color of a GridView item in an Android application written in Kotlin. It allows the user to select an item from the grid, and upon selection, the chosen item's background color changes to indicate its selection.
The code is divided into two main parts: the MainActivity.kt
file handling the logic and the activity_main.xml
file defining the layout.
Breakdown and Functionality
MainActivity.kt:
- Defines variables for plant names (
list
), background colors for regular and selected items (itemBackgroundColor
,selectedItemBackgroundColor
), and the grid view's background color. - Creates an
ArrayAdapter
for the GridView, populating it with the plant list. In thegetView
method, it sets the text, gravity, and background color for each item in the grid. - Attaches an
setOnItemClickListener
to the GridView. This listener gets triggered whenever a grid item is clicked. - Inside the listener, it:
- Retrieves the clicked item's text.
- Displays the selected item's text in a separate TextView below the grid.
- Loops through all items in the GridView and sets their background colors based on whether they are the selected item or not.
- Defines variables for plant names (
activity_main.xml:
- Defines the layout using a ConstraintLayout.
- Includes a GridView with two columns and spacing between items.
- Positions the GridView and a TextView below it within the layout.
Summary
This code provides a clear example of customizing the visual feedback for user interaction in a GridView. By changing the background color of the selected item, the user receives a clear indication of their choice within the grid.
MainActivity.kt
package com.example.jetpack
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.get
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(
"Catalina ironwood",
"Cabinet cherry",
"Pale corydalis",
"Pink corydalis",
"Belle Isle cress",
"Land cress",
"Orange coneflower",
"Water fern"
)
// specify the items background color
val itemBackgroundColor = Color.parseColor("#E60026")
val selectedItemBackgroundColor = Color.parseColor("#FFDB00")
// grid view background color
gridView.setBackgroundColor(Color.parseColor("#FB4D46"))
// array adapter for grid view
gridView.adapter = object : ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,list){
override fun getView(position: Int, convertView: View?,
parent: ViewGroup): View {
return (super.getView(position, convertView, parent) as TextView)
.apply {
text = list[position]
gravity = Gravity.CENTER
// grid view vertical spacing, horizontal spacing and
// item background color together make border between items
setBackgroundColor(itemBackgroundColor)
}
}
}
// 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
// loop through the adapter view items
for (index in 0 until adapterView.count){
adapterView[index].apply {
if (index != i){
// background color for not selected items
setBackgroundColor(itemBackgroundColor)
}else{
// background color for selected item
setBackgroundColor(selectedItemBackgroundColor)
}
}
}
}
}
}
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="24dp"
android:layout_marginEnd="8dp"
android:numColumns="2"
android:horizontalSpacing="3dp"
android:verticalSpacing="3dp"
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="16dp"
android:textColor="#004F98"
android:textSize="30sp"
android:fontFamily="sans-serif-condensed-medium"
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 - Border/divider between GridView items
- android kotlin - GridView OnItemClickListener