Android Checkbox List is always checking the first item

250 views Asked by At

I have to show the checkbox checked when some condition is true. But my Adapter is always checking the first checkbox. I dont know why.

My ListView Adapter:

class SampleAdapter() : BaseAdapter() {

    val list: MutableList<String> = mutableListOf(
            "ITEM 1", "ITEM 2", "ITEM 3", "ITEM 4", "ITEM 5" )

    override fun getView(position: Int, view: View?, parent: ViewGroup): View {
        var convertView = view
        val result: View

        if (convertView == null) {
            convertView = LayoutInflater.from(parent.context)
                    .inflate(R.layout.sample_checkbox, parent, false)
            result = convertView
        } else {
            result = convertView
        }

        val item: String = getItem(position)
        result.checkBox.text = item

        if(item == "ITEM 5") result.checkBox.isChecked = true

        return result
    }    

    override fun getCount(): Int { return list.size }    
    override fun getItem(position: Int): String { return list[position] }    
    override fun getItemId(p0: Int): Long { return 0 }
}

The Result:

enter image description here

The Problem: I expect to see only the item 5 checked (item == "ITEM 5"). But is checking the first item too, as you can see above.

1

There are 1 answers

0
Nezih Yılmaz On BEST ANSWER

Adapters require you to cover other conditions too. So add an else statement like this:

if(item == "ITEM 5") result.checkBox.isChecked = true
else result.checkBox.isChecked = false

You can reduce this code to single line if you like