android列表侧滑删除&置顶,安卓开发项目实例
作者:互联网
android:orientation=“vertical”>
</com.mcxtzhang.swipemenulib.SwipeMenuLayout>
适配器中的代码,就是普通的RecyclerView适配器,我们只需要把删除、置顶的两个点击回调,写2个对应删除、置顶的方法即可。删除方法,就是list集合删除当前的position,然后notifyDataSetChanged一下就可以了,置顶方法就是list集合,添加当前的position到集合的起始位置。
class SampleAdapter(val list: ArrayList): RecyclerView.Adapter<SampleAdapter.ViewHolder>() {
inner class ViewHolder(view:View):RecyclerView.ViewHolder(view){
val tvName:TextView=view.findViewById(R.id.tvName)
val btnTop:TextView=view.findViewById(R.id.btnTop)
val btnDelete:TextView=view.findViewById(R.id.btnDelete)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SampleAdapter.ViewHolder {
val view=LayoutInflater.from(parent.context).inflate(R.layout.item_sample,parent,false)
return ViewHolder(view)
}
override fun getItemCount()=list.size
override fun onBindViewHolder(holder: SampleAdapter.ViewHolder, position: Int) {
holder.tvName.setText(list.get(position))
//删除按钮
holder.btnDelete.setOnClickListener {
onItemClickDelete.invoke(it,position)
}
//置顶按钮
holder.btnTop.setOnClickListener {
onItemClickTop.invoke(it,position)
}
}
//删除
fun delete(position: Int){
list.removeAt(position)
notifyDataSetChanged()
}
//置顶
fun top(position: Int){
list.add(0,list.removeAt(position))
notifyDataSetChanged()
}
lateinit var onItemClickDelete: (v: View, pos: Int) -> Unit//删除
lateinit var onItemClickTop: (v: View, pos: Int) -> Unit//置顶
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:app=“http://schemas.android.com/apk/res-auto”
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_sample"
android:layout_width=“match_parent”
android:layout_height=“match_parent”/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainAcivity
class MainActivity : AppCompatActivity() {
private lateinit var rvSample:RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rvSample=findViewById(R.id.rv_sample)
//布局管理器
val layoutManager=LinearLayoutManager(this)
layoutManager.orientation=LinearLayoutManager.VERTICAL
rvSample.layoutManager=layoutManager
val list=ArrayList()
//集合添加数据
标签:parent,安卓,list,position,android,置顶,view 来源: https://blog.csdn.net/m0_65146105/article/details/121872955