Kotlin中点击recyclerview的子项时删除数据库中某张表的记录
时间: 2023-08-02 14:07:23 浏览: 166
首先,你需要在你的RecyclerView的Adapter中实现一个接口,该接口用于在点击RecyclerView的子项时告知Activity或Fragment。例如:
```kotlin
interface OnItemClickListener {
fun onItemClick(position: Int)
}
```
然后,在你的Adapter中添加一个方法,用于设置该接口:
```kotlin
class MyAdapter(private val listener: OnItemClickListener) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
//...
fun setOnItemClickListener(listener: OnItemClickListener) {
this.listener = listener
}
//...
}
```
现在,在你的ViewHolder中为子项设置点击事件,当点击子项时,调用OnItemClickListener接口的onItemClick方法,并将子项的位置作为参数传递给Activity或Fragment:
```kotlin
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position)
}
}
}
//...
}
```
接下来,在你的Activity或Fragment中实现OnItemClickListener接口,并在onCreate方法中为RecyclerView的Adapter设置该接口:
```kotlin
class MyActivity : AppCompatActivity(), OnItemClickListener {
private lateinit var myAdapter: MyAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my)
myAdapter = MyAdapter(this)
recyclerView.adapter = myAdapter
myAdapter.setOnItemClickListener(this)
}
override fun onItemClick(position: Int) {
// 在这里删除数据库中的记录
}
//...
}
```
最后,在onItemClick方法中,使用你的数据库的API删除该记录,例如:
```kotlin
override fun onItemClick(position: Int) {
val item = myAdapter.getItem(position)
val db = MyDatabaseHelper(applicationContext).writableDatabase
db.delete("my_table", "id = ${item.id}", null)
myAdapter.removeItem(position)
}
```
其中,getItem和removeItem方法用于获取和删除RecyclerView的指定位置的子项。
阅读全文