How to Change Background Color of ListView Items in Android?
In Android, a ListView is a layout element that is used to display items in a list. This is the simplest form of displaying a list or array of items and one can choose from pre-developed layouts for displaying an element without creating a separate layout unlike in other similar views. Each item in this view is a separate layout and differentiated by a horizontal stroke.
In this article, we will show you how you could change the background of the item layout in the ListView on click in Android. Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a ListView as shown below.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout 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" > < ListView android:id = "@+id/list_view_1" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </ RelativeLayout > |
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package org.w3wiki.lvitembgchngonclick import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ListView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Creating a list of items val mList = arrayOf( "Android" , "IOS" , "Windows" , "BlackberryOS" , "WebOS" , "Ubuntu" , "Windows7" , "Max OS X" ) // Declaring and initializing the ListView from // the layout and setting an adapter to display the list val mListView = findViewById<ListView>(R.id.list_view_1) mListView.adapter = ArrayAdapter( this , android.R.layout.simple_list_item_1, mList) // Change the item layout background on touch to red mListView.onItemClickListener = AdapterView.OnItemClickListener { _, view, _, _ -> view.setBackgroundColor(Color.RED) } } } |
Output:
You can see that when we touch/click any item, the layout background of that item changes to red.
Contact Us