我有一个数据类,其中包含一个名为“prio”的成员(下面的示例)。此“prio”应创建recyclerView如何显示项目的顺序-应在rv的顶部显示编号为1的“prio”,在编号1下方显示编号2,依此类推。
附加信息:但是用户可以决定该商品应具有的编号(优先级)。因此,“prio”不是固定的。
数据类
data class TaskModel(
val id: Int,
val task: String,
var prio: Int
)
问题:是否可以帮助我创建一个对“prio”进行排序的函数,并按照recyclerView显示项目的顺序在recyclerView中初始化此函数?附件:
适配器:
open class TaskAdapter (private val context: Context, private val list: ArrayList<TaskModel>)
: RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val mTaskDetails : TaskModel? = null
private var onClickListener: OnClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return MyViewHolder(
LayoutInflater.from(context).inflate(R.layout.activity_item_adapter, parent, false)
)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val model = list[position]
if (holder is MyViewHolder) {
holder.itemView.tv_task_name.text = model.task
if(model.prio == 1){
holder.itemView.tv_priority.setBackgroundColor(Color.parseColor("#DF0101"))
}else if (model.prio == 2){
holder.itemView.tv_priority.setBackgroundColor(Color.parseColor("#FFFF00"))
}else if (model.prio == 3){
holder.itemView.tv_priority.setBackgroundColor(Color.parseColor("#31B404"))
}
//holder.itemView.tv_priority.text = model.prio
holder.itemView.setOnClickListener{
if(onClickListener != null){
onClickListener!!.onClick(position,model)
}
}
}
}
private class MyViewHolder(view: View) : RecyclerView.ViewHolder(view)
//RecyclerView Klickbar machen
interface OnClickListener {
fun onClick(position: Int, model: TaskModel)
}
MainActivity private fun setupTaskRecyclerView(tasklist: ArrayList<TaskModel>){
rv_task_view.layoutManager = LinearLayoutManager(this)
rv_task_view.setHasFixedSize(true)
val taskAdapter = TaskAdapter(this, tasklist)
rv_task_view.adapter = taskAdapter
}
最佳答案
您可以先将sort
编码为array
,然后再传递给adapter
,如下所示:
tasklist.sortBy { it.prio }
您的代码将如下更改: private fun setupTaskRecyclerView(tasklist: ArrayList<TaskModel>){
rv_task_view.layoutManager = LinearLayoutManager(this)
rv_task_view.setHasFixedSize(true)
tasklist.sortBy { it.prio }
val taskAdapter = TaskAdapter(this, tasklist)
rv_task_view.adapter = taskAdapter
}