当用户按下ListView的某个元素(而不是按钮)时,它可以正常工作,并且android显示Toast:“未单击按钮,$ position可以正常工作”
但是当在特定的listView元素中单击按钮时,我还需要烤面包(并获取按钮的位置)。我尝试在view.imageViewButton.setOnClickListener
内使用listV.setOnItemClickListener
,但是在这种情况下,只有在我单击按钮左侧的空白后,该按钮才起作用。
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()
}
onCreate(savedInstanceState: Bundle?)
开始时我应该如何激活按钮?
我的Kotlin代码:
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()
}
}
答案 0 :(得分:3)
您可以扩展SimpleCursorAdapter来将点击侦听器设置为特定视图
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")
}
}
}
}
}
但是我建议您使用RecyclerView而不是ListView。
ListView是老式的,不建议使用
希望它会有所帮助:)