'How to set the background color of all ListView Items

I have got the following for setting the background color for a single item when clicking on it:

        // Get the listView on the Home Fragment
        val contactList = findViewById<ListView>(R.id.listViewContacts)
        // Create IDs for each element
        val id : Int = R.id.txtListElement

        // Fill the ListView with the custom contact_list_template
        arrayAdapter = ArrayAdapter(this,
            R.layout.contact_list_template, id, contactSimple)
        contactList.adapter = arrayAdapter

        contactList.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view,
                                                                            position, _ ->
            val selectedItem = adapterView.getItemAtPosition(position) as String
            val itemIdAtPos = adapterView.getItemIdAtPosition(position)


            view.setBackgroundColor(ContextCompat.getColor(this, R.color.purple_200))
            ...
        }

But how can I set the color for every object inside the ListView? I tried contactList.setBackgroundColor(ContextCompat.getColor(this, R.color.white)) but that does not seem to work.



Solution 1:[1]

Try to define your custom BaseAdapter for the ListView. (I assume that the contact_list_template XML contains a TextView with id title).

class ListViewContactAdapter(
    private val contactList: List<String>
) : BaseAdapter() {

    private val lastClicked = ""

    override fun getCount(): Int = contactList.size

    override fun getItem(position: Int): String = contactList[position]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view = convertView ?: LayoutInflater.from(parent.context).inflate(R.layout.contact_list_template, parent, false)

        val holder = ViewHolderContact(view)
        val contact = getItem(position)

        holder.title.text = contact

        if (contact == lastClicked) {
            // Selected background
            view.setBackgroundColor(ContextCompat.getColor(this, ...))
        } else {
            // Unselected background
            view.setBackgroundColor(ContextCompat.getColor(this, ...))
        }

        view.setOnClickListener { 
            lastClicked = contact
            notifyDataSetChanged()
        }

        return view
    }

    class ViewHolderContact(itemView: View) {
        val title = itemView.findViewById<TextView>(R.id.title)
    }
}

You can then set the adapter of the list with:

val contactList = findViewById<ListView>(R.id.listViewContacts)
contactList.adapter = ListViewContactAdapter(contactSimple)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lpizzinidev