activity kotlin RecyclerView 左滑显示删除按钮删除item 完整代码实现
时间: 2023-06-17 20:03:05 浏览: 162
下面是一个基于 Kotlin 和 RecyclerView 实现左滑显示删除按钮删除 item 的示例代码:
1. 在 build.gradle 文件中添加 RecyclerView 依赖:
```
implementation 'androidx.recyclerview:recyclerview:1.2.0'
```
2. 在布局文件中添加 RecyclerView:
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
3. 创建 RecyclerView 的 adapter:
```
class MyAdapter(private val items: MutableList<String>) :
RecyclerView.Adapter<MyAdapter.ViewHolder>(), ItemTouchHelperAdapter {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int {
return items.size
}
override fun onItemMove(fromPosition: Int, toPosition: Int) {
Collections.swap(items, fromPosition, toPosition)
notifyItemMoved(fromPosition, toPosition)
}
override fun onItemDismiss(position: Int) {
items.removeAt(position)
notifyItemRemoved(position)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val textView: TextView = itemView.findViewById(R.id.textView)
private val deleteButton: Button = itemView.findViewById(R.id.deleteButton)
private val itemLayout: LinearLayout = itemView.findViewById(R.id.itemLayout)
fun bind(item: String) {
textView.text = item
deleteButton.setOnClickListener {
// 删除当前项
adapterPosition.takeIf { it != RecyclerView.NO_POSITION }?.also { position ->
(itemView.context as MainActivity).deleteItem(position)
}
}
itemLayout.translationX = 0f
itemLayout.setOnTouchListener(object : View.OnTouchListener {
private var initialX = 0f
private var lastX = 0f
private val slop = ViewConfiguration.get(itemView.context).scaledTouchSlop
override fun onTouch(v: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
initialX = event.x
lastX = event.x
}
MotionEvent.ACTION_MOVE -> {
val dx = event.x - initialX
if (Math.abs(dx) > slop) {
itemLayout.translationX = dx
}
lastX = event.x
}
MotionEvent.ACTION_UP -> {
val dx = lastX - initialX
val threshold = itemLayout.width * 0.5f
if (Math.abs(dx) > threshold) {
(itemView.context as MainActivity).deleteItem(adapterPosition)
} else {
itemLayout.animate().translationX(0f).duration = 100
}
}
}
return true
}
})
}
}
}
```
4. 在 MainActivity 中使用 RecyclerView:
```
class MainActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: MyAdapter
private lateinit var touchHelper: ItemTouchHelper
private val items = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 初始化 RecyclerView
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
adapter = MyAdapter(items)
recyclerView.adapter = adapter
// 添加测试数据
for (i in 1..20) {
items.add("Item $i")
}
adapter.notifyDataSetChanged()
// 添加左滑删除功能
touchHelper = ItemTouchHelper(MyItemTouchHelperCallback(adapter))
touchHelper.attachToRecyclerView(recyclerView)
}
fun deleteItem(position: Int) {
adapter.onItemDismiss(position)
}
}
```
5. 创建 ItemTouchHelperAdapter 接口和 MyItemTouchHelperCallback 类:
```
interface ItemTouchHelperAdapter {
fun onItemMove(fromPosition: Int, toPosition: Int)
fun onItemDismiss(position: Int)
}
class MyItemTouchHelperCallback(private val adapter: ItemTouchHelperAdapter) :
ItemTouchHelper.Callback() {
override fun isLongPressDragEnabled(): Boolean {
return true
}
override fun isItemViewSwipeEnabled(): Boolean {
return true
}
override fun getMovementFlags(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
): Int {
val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
val swipeFlags = ItemTouchHelper.START or ItemTouchHelper.END
return makeMovementFlags(dragFlags, swipeFlags)
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
adapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
adapter.onItemDismiss(viewHolder.adapterPosition)
}
}
```
完成以上步骤后,就可以左滑删除 RecyclerView 中的 item 了。
阅读全文