Kotlin setOnClickListener for a ListView
14,278
Solution 1
You have to handle all the parameters for AdapterView.OnItemClickListener
Your listener should look like this:
listView.setOnItemClickListener { parent, view, position, id ->
val element = adapter.getItemAtPosition(position) // The item that was clicked
val intent = Intent(this, BookDetailActivity::class.java)
startActivity(intent)
}
Solution 2
Try this solution for listview item click listener.
listView.setOnItemClickListener = AdapterView.OnItemClickListener {parent,view, position, id ->
// Get the selected item text from ListView
val selectedItem = parent.getItemAtPosition(position) as String
val intent = Intent(this, BookDetailActivity::class.java)
startActivity(intent)
}
Author by
Lechucico
Updated on June 18, 2022Comments
-
Lechucico almost 2 years
I have the following code:
class BookListActivity : AppCompatActivity() { var array = arrayOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10", "Item 11") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.book_list) val adapter = ArrayAdapter(this, R.layout.book_list_item, R.id.book_title, array) val listView : ListView = findViewById(R.id.book_list) listView.adapter = adapter } }
I need to add a click listener for each element on the listView.
I've tried the following but doesn't work:
listView.setOnItemClickListener { val intent = Intent(this, BookDetailActivity::class.java) startActivity(intent) }
Also I need to know what ListView element I've clicked. How can I do this?
-
AW5 almost 3 yearsI would rather do
parent.getItemAtPosition(position)