androidlistviewkotlin

How to perform click on button of ListView element in Android


I have listView and each element contains 1 button enter image description here

When user presses some element of ListView (but not button) it works correctly and android shows toast: "Not button clicked, $position works correctly"

But I also need to make toast (and get position of button) when button is clicked in specific listView element. I tried to use view.imageViewButton.setOnClickListener inside of listV.setOnItemClickListener but in this scenario button worked only after I clicked a blank space to the left of the button.

listV.setOnItemClickListener { parent, view, position, id ->
  //I tried you use comented line to solwe my problem
  //view.imageViewButton.setOnClickListener { Toast.makeText(this, "button $position is clicked",Toast.LENGTH_SHORT).show() }
  Toast.makeText(this, "not button clicked, works correctly", Toast.LENGTH_SHORT).show()
} 

How should I do to activate buttons when onCreate(savedInstanceState: Bundle?) starts?

My kotlin code:

class MainActivity : AppCompatActivity() {

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

    var db = DataBaseHelper(this)
    var cursor = db.returnLines()

    listV.adapter = SimpleCursorAdapter(this,
        R.layout.view_holder,
        cursor,
        arrayOf("imia"),
        intArrayOf(R.id.listNameView),
        0)

    listV.setOnItemClickListener { parent, view, position, id ->

      //I tried you use comented line to solwe my problem
      //view.imageViewButton.setOnClickListener { Toast.makeText(this, "button $position is clicked",Toast.LENGTH_SHORT).show() }
      Toast.makeText(this, "not button clicked, $position works correctly", Toast.LENGTH_SHORT).show()
    }
}

Solution

  • You can extend SimpleCursorAdapter to set click listener to specific view

    class CustomAdapter(context: Context?, layout: Int, c: Cursor?, from: Array<out String>?, to: IntArray?) : SimpleCursorAdapter(context, layout, c, from, to) {
    
        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            return super.getView(position, convertView, parent).apply {
                if (convertView == null) { // This means newView()
                    findViewById<View>(R.id.image_view).setOnClickListener {
                        Toast.makeText(context, "image view clicked pos=$position")
                    }
                }
            }
        }
    }
    

    But I recommend you to use RecyclerView instead of ListView.

    ListView is old-fashioned and deprecated to use

    Hope it helps :)