如何使用Kotlin的自定义适配器为列表视图设置OnItemClickListener

我使用我的Android应用程序列表视图的自定义适配器。 我不知道如何设置监听器的项目点击。 我使用Kotlin作为我的应用程序。

这是我的适配器布局。

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <CheckBox android:id="@+id/cbx" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" /> <TextView android:id="@+id/txtNameNote" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:layout_toRightOf="@+id/cbx" /> <TextView android:id="@+id/txtPercent" android:layout_width="wrap_content" android:layout_height="match_parent" android:text="TextView" android:layout_toRightOf="@+id/cbx" android:layout_below="@+id/txtNameNote" /> </RelativeLayout> </LinearLayout> 

这是我的适配器代码

 class CustomAdapter(internal var context: Context, resource: Int, internal var listNote: ArrayList<Note>) : ArrayAdapter<Note>(context, resource, listNote) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView // TODO Auto-generated method stub val inflater = (context as Activity).layoutInflater convertView = inflater.inflate(R.layout.rowlistitem, parent, false) val name = convertView!!.findViewById<View>(R.id.txtNameNote) as TextView val percent = convertView.findViewById<View>(R.id.txtPercent) as TextView val cb = convertView.findViewById<View>(R.id.cbx) as CheckBox name.text = listNote[position].name percent.text = "Percent: " + listNote[position].percent + "%" if (listNote[position].status == NoteStatus.Active.value) cb.isChecked = false else{ name.paintFlags = (name.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG) cb.isChecked = true } } } return convertView } } 

有人可以帮我吗?

Kotlin的正确方法是创建一个回调。 然后,在适配器中创建一个点击监听器,并将结果转发给您的回调。

 class CustomAdapter( internal var context: Context, resource: Int, internal var listNote: ArrayList<Note>, val callback: (Note) -> Unit) : ArrayAdapter<Note>(context, resource, listNote) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { // .. do your bindings whatever convertView.yourRootLayoutElement.setOnClickListener{ if (callback != null) callback(listNote[position]) } return convertView } } 

在您创建适配器的视图中

 CustomAdapter(...., { info { "Clicked $it" } }) 

我没有测试过,因为我不使用ListView。 我建议你使用RecyclerView。 ListView被弃用 ,不推荐有几个原因。

编辑:绝对没有理由在RecyclerView上使用ListView。 即使它有效,你也不应该使用它。 学习RecyclerView,因为ListView 不再使用。