简体   繁体   中英

Change ListView item background color programmatically

Let's say we have ListView of basic text items:

package cz.nanuq.test

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Init listView
        val listView = findViewById<ListView>(R.id.listView)

        var values : Array<String> = arrayOf("foo", "bar", "baz", "boo")
        var adapter : ArrayAdapter<String> = ArrayAdapter(this, android.R.layout.simple_list_item_1, values)
        listView.setAdapter(adapter)

        // Change background color of one listView item
        var index : Int = 2               // can change dynamically
        var bgColor : String = '#123456'  // can change dynamically
        //...how? 
    }

}

Now I want to change background color of item with index 2 to "#123456".

How to do that?


PS For this simple task I'm looking for simple solution. Something like:

listView.getItem(index).setAttribute("background", bgColor)

Basically I just need to access ListView's sub-component and change it's attribute.

I just used code from question And got expected result. This definitely helps & Simplest way. we can implement the adapter and change the views like we want. Please try the below code.

import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView

class MainActivity : AppCompatActivity() {

    private val values: Array<String> = arrayOf("foo", "bar", "baz", "boo")

    // Change background color of one listView item
    private var index: Int = 0               // can change dynamically®
    private var bgColor: String = "#ffffff"  // can change dynamically

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Init listView
        val listView: ListView = findViewById(R.id.listView)

        val adapter: ArrayAdapter<String> =
            object : ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values) {
                override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                    val v = super.getView(position, convertView, parent)

                    val tv = v.findViewById<TextView>(android.R.id.text1)

                    if (index == position) {
                        tv.setBackgroundColor(Color.parseColor(bgColor))
                        tv.setTextColor(Color.WHITE)
                    } else {
                        tv.setBackgroundColor(Color.TRANSPARENT)
                        tv.setTextColor(Color.BLACK)
                    }

                    return v
                }
            }

        listView.adapter = adapter


        // For -- Explanation / testing purpose, I used handler here.
        update(adapter)
    }

    private fun update(adapter: ArrayAdapter<String>) {

        // For -- Explanation / testing purpose, I used handler here.

        Handler().postDelayed({
            index = 0
            bgColor = "#123456"
            adapter.notifyDataSetChanged()
        }, 1000)

        Handler().postDelayed({
            index = 1
            bgColor = "#c544fc"
            adapter.notifyDataSetChanged()
        }, 2000)

        Handler().postDelayed({
            index = 2
            bgColor = "#123456"
            adapter.notifyDataSetChanged()
        }, 3000)

        Handler().postDelayed({
            index = 3
            bgColor = "#c544fc"
            adapter.notifyDataSetChanged()

            // For -- Explanation / testing purpose, (REPEATING / LOOPING).
            update(adapter)
        }, 4000)
    }
}

The result as follows. Happy Coding :)

Divakar Murugesh的答案

If you want to change the background color of a specific item, you need to set it inside your onBindViewHolder method in your CustomAdapter class. This is my code for setting the 5th item of my recyclerview.

 @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        ProfileDetails profileDetails = profileDetailsList.get(position);
        holder.icon.setImageResource(profileDetails.getIcon());
        holder.label.setText(profileDetails.getLabel());
        holder.details.setText(profileDetails.getDetail());

        if(position == 4)
        {
            holder.details.setMaxLines(3);
            holder.itemView.setBackgroundColor(R.drawable.btn_border);
            holder.details.setMinHeight(90);
            holder.itemView.setMinimumHeight(90);
            holder.itemView.setPadding(0,20,0,50);
        }
    }

holder.details.setMaxLines(3) is my code for programmatically setting the maxLines of the TextView of my 5th item. Other textView is set to 1 as their maxLines.

holder.itemView.setBackgroundColor(R.drawable.btn_border); is my code to set the background of my 5th item. Note that you need to create a drawable for your color. This won't work if you just set a color from color.xml.

holder.itemView.setMinimumHeight(90); is my code to manipulate the height of the TextView and holder.itemView.setPadding(0,20,0,50); for the padding left, padding top, padding right and padding bototm.

Refer to the screenshot below for the final output.

回收站视图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM