Introduction
This code demonstrates how to set a custom height for items displayed within a GridView in an Android application written in Kotlin. The code defines a GridView
containing a list of plant names. It then programmatically sets the height of each item in the grid and adds functionalities like displaying the clicked item's text in a separate TextView.
Breakdown
The code is divided into two main parts: the Kotlin class (MainActivity.kt
) and the layout file (activity_main.xml
).
MainActivity.kt
Data and Setup:
- A list of plant names is created.
- The desired item height in dp (density-independent pixels) is converted to pixels using an extension function.
GridView Adapter:
- A custom
ArrayAdapter
subclass is created to handle the grid view items. - The
getView
method inflates the default layout for the adapter and customizes it:- Sets the item text from the data list.
- Centers the text within the item.
- Sets background color and spacing to create a border effect between items.
- Sets the item height in pixels using the previously calculated value.
- A custom
GridView Configuration:
- The adapter is set to the GridView.
- An on-click listener is set for the GridView.
- When an item is clicked, its text is retrieved and displayed in a separate TextView below the grid.
activity_main.xml
- This file defines the layout for the activity.
- It uses a ConstraintLayout as the root element.
- The
GridView
is defined with the following properties:- Two columns.
- Horizontal and vertical spacing between items.
- Wrap content height.
- A TextView is placed below the GridView to display the clicked item's text.
Summary
This code provides a practical example of customizing the appearance of GridView items in an Android app using Kotlin. By creating a custom adapter and leveraging an extension function for unit conversion, the code achieves a visually appealing grid layout with consistent item heights.
package com.example.jetpack
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.TypedValue
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 kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// mutable list of plants to populate grid view
val list = mutableListOf(
"Catalina ironwood",
"Cabinet cherry",
"Pale corydalis",
"Pink corydalis",
"Belle Isle cress",
"Orange coneflower",
"Coast polypody",
"Water fern"
)
// set the grid view item height in dp and convert it to pixels
val itemHeight = 90.dpToPixels(this)
// array adapter for grid view
val 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(Color.parseColor("#7DF9FF"))
// set grid view item height in pixels
layoutParams.height = itemHeight
}
}
}
gridView.adapter = adapter
// 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
}
}
}
// extension function to convert dp to equivalent pixels
fun Int.dpToPixels(context: Context):Int = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,this.toFloat(),context.resources.displayMetrics
).toInt()
<?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="#F0FFFF">
<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="#8BA8B7"
android:horizontalSpacing="3dp"
android:numColumns="2"
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 - GridView add item dynamically
- android kotlin - GridView selected item background color
- android kotlin - Border/divider between GridView items
- android kotlin - GridView OnItemClickListener
- android kotlin - Set CardView background color
- android kotlin - Set CardView corner radius
- android kotlin - RadioButton with image and text
- android kotlin - RadioGroup onCheckedChange listener
- android kotlin - Get RadioGroup selected item
- android kotlin - RadioButton onClick event
- android kotlin - TextView add Hyperlink programmatically
- android kotlin - TextView get width height programmatically
- android kotlin - TextView html formatted text
- android kotlin - Coroutines async with timeout
- android kotlin - Coroutines with timeout