【Kotlin】 列表适配器
列表的显示和操作
定义操作接口,只定义编辑和删除的功能,其他的功能可以类似扩展
/** * 列表中项的操作 */ interface ItemOperatorAdapter<T> { /** * 删除 */ fun onDelete(t: T) /** * 编辑 */ fun onEdit(t: T) }
定义RecyclerView列表适配器
定义页面的控件
<androidx.recyclerview.widget.RecyclerView android:id="@+id/rv_Content_setting_account" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/app_white" />
定义列表适配器
class AccoutListItemAdapter( private val data: List<AccountEntity>, private val operator: ItemOperatorAdapter<AccountEntity> ) : RecyclerView.Adapter<AccoutListItemAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( RvAccoutContentItemBinding.inflate( LayoutInflater.from( parent.context ), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindData(data[position], operator) } class ViewHolder(private val binding: RvAccoutContentItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bindData(item: AccountEntity, operator: ItemOperatorAdapter<AccountEntity>) { binding.tvPauseNumber.text = "67" } } override fun getItemCount(): Int { return data.size } }
mvvm绑定
val inventoryListItemAdapter = AccoutListItemAdapter(testList, object : ItemOperatorAdapter<AccountEntity> { override fun onDelete(t: AccountEntity) { val customDialog = CustomDialog(requireActivity()) customDialog.setsTitle("温馨提示").setsMessage("是否删除(${t.nick_name})账号?") .setsCancel("取消", View.OnClickListener { customDialog.dismiss() }).setsConfirm("确定", View.OnClickListener { viewModel.delete(t)//删除用户 customDialog.dismiss() }).show() } override fun onEdit(t: AccountEntity) { showEditAccountPopWindow(t) } }) binding.rvContentSettingAccount.adapter = inventoryListItemAdapter