How to change background color of selected item in listview in Android ?

ยท 161 words ยท 1 minute read

The main idea is to use view.setBackgroundColor(getColor(R.color.colorAccent)) to the selected view (list item). Let’s see a complete example.

  1. use this xml code in res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="8dp"
   tools:context=".MainActivity">
<ListView
   android:id="@+id/listView"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />
</RelativeLayout>
  1. use this Kotlin code in src/MainActivity.kt.
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
class MainActivity : AppCompatActivity() {
   var operatingSystem: Array<String> = arrayOf("Android", "IPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X")
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val listView: ListView = findViewById(R.id.listView)
      val adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, operatingSystem)
      listView.adapter = adapter
      listView.setOnItemClickListener { _, view, _, _ ->
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            view.setBackgroundColor(getColor(R.color.colorAccent))
         }
      }
   }
}

Run the application. When you touch / tap / press on a list item its background color will change. That’s it. If you know somebody need this post, share it with him/her via Facebook / twitter / whatsapp / reddit / email / .. etc.

Share:
waffarx cash back