我正在使用一个小应用程序,并使用带有图像和标题的自定义列表视图,但是我无法使OnItemClickListener
工作。我一直在遵循不同的指南,并且列表运行良好,但是在OnItemClickListener
中经常出现错误。
有人可以帮我这个忙吗
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val listView = findViewById<ListView>(R.id.lvMain)
listView.adapter = MyAdapter(this)
listView.setOnItemClickListener( ... ){ <-- Where everything goes wrong
}
}
private class MyAdapter(context: Context) : BaseAdapter() {
val lvIcon = arrayOf(R.drawable.asterisk, R.drawable.numeric, R.drawable.billiards, R.drawable.dice_6, R.drawable.coin, R.drawable.palette)
val lvList = arrayOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6")
private val mContext: Context = context
override fun getView(i: Int, convertView: View?, parent: ViewGroup?): View {
val layout = LayoutInflater.from(mContext)
val rows = layout.inflate(R.layout.listview_rows, parent, false)
val listItems = rows.findViewById<TextView>(R.id.lv_list)
val iconItems = rows.findViewById<ImageView>(R.id.lv_icon)
listItems.text = lvList.get(i)
iconItems.setImageResource(lvIcon[i])
return rows
}
override fun getItem(position: Int): Any {
return "STRING" //To change body of created functions use File | Settings | File Templates.
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return lvList.count()
}
}
}
答案 0 :(得分:0)
您不需要括号(...)
listView.setOnItemClickListener{
// your code here
}
您应该考虑在科特林学习lambdas
答案 1 :(得分:0)
使用此
listView.setOnItemClickListener { parent, view, position, l ->
//your code
Toast.makeText(applicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}