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:
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.
Adapters require you to cover other conditions too. So add an else statement like this:
You can reduce this code to single line if you like