activity kotlin RecyclerView 左滑删除item 全部代码实现 详细
时间: 2023-06-16 20:04:08 浏览: 209
以下是 Kotlin 实现 RecyclerView 左滑删除 item 的完整代码:
1. 在布局文件中添加 RecyclerView:
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 创建 RecyclerView 的 Adapter 类:
```
class MyAdapter(private val itemList: MutableList<String>) :
RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemText: TextView = itemView.findViewById(R.id.itemText)
val deleteBtn: ImageButton = itemView.findViewById(R.id.deleteBtn)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_layout, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.itemText.text = itemList[position]
holder.deleteBtn.setOnClickListener {
itemList.removeAt(position)
notifyItemRemoved(position)
}
}
override fun getItemCount(): Int {
return itemList.size
}
}
```
3. 在 Activity 或 Fragment 中初始化 RecyclerView:
```
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
val itemList = mutableListOf<String>("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
val adapter = MyAdapter(itemList)
recyclerView.adapter = adapter
val itemTouchHelper = ItemTouchHelper(itemTouchHelperCallback)
itemTouchHelper.attachToRecyclerView(recyclerView)
```
4. 创建 ItemTouchHelper.Callback 类,并实现左滑删除的逻辑:
```
val itemTouchHelperCallback = object : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
val dragFlags = 0
val swipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
return makeMovementFlags(dragFlags, swipeFlags)
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
itemList.removeAt(position)
adapter.notifyDataSetChanged()
}
}
```
5. 最后,记得在 RecyclerView 的 item 布局文件中添加左滑删除按钮:
```
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/itemText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="16dp"
android:textSize="18sp" />
<ImageButton
android:id="@+id/deleteBtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="@null"
android:padding="16dp"
android:src="@drawable/ic_delete" />
</LinearLayout>
```
以上就是 RecyclerView 左滑删除 item 的完整代码实现。
阅读全文