首页 > 解决方案 > Recyclerview Item对象在主类中设置函数

问题描述

我正在编写待办事项列表并使用 Groupie 适配器。我创建了一个 ViewHolder 类“TaskItem”。在该 ViewHolder 类中,我正在设置布局,在绑定功能上,我正在设置 Item 应显示的文本。此项目有两个按钮,出于多种原因,我想在将项目添加到适配器的主类中访问它们。我是如何找到解决方案的,但它是一个非常糟糕的解决方案:我使用了函数 adapter.setOnItemClickListener ,我在其中执行了所有其他功能,如其他点击列表器等。一切基本上都是这样工作的,但你必须先点击整个项目,直到项目中的按钮是可点击的。

我需要一个其他函数来解决这个问题,比如 adapter.bindViewHolder 但我不知道要传递哪些参数以及从哪里得到这些参数。

    val tasksAdapter = GroupAdapter<ViewHolder>()  
    val recyclerViewTasks = findViewById<RecyclerView>(R.id.recyclerViewTasks)
    recyclerViewTasks.adapter = tasksAdapter

    tasksAdapter.setOnItemClickListener { item, view ->
        val taskTextView = view.findViewById<TextView>(R.id.taskTextView)
        val editTaskButton = view.findViewById<ImageButton>(R.id.buttonEditTask)
        val taskCheckBox = view.findViewById<CheckBox>(R.id.taskCheckBox)

        editTaskButton.setOnClickListener {
            val editLayout = findViewById<View>(R.id.LayoutEdit)
            editLayout.visibility = View.VISIBLE
            val taskEditText = findViewById<EditText>(R.id.editTextTask)
            val exitButton = findViewById<ImageButton>(R.id.buttonExitTask)
            val deleteButton = findViewById<ImageButton>(R.id.buttonDeleteTask)
            val confirmButton = findViewById<ImageButton>(R.id.buttonConfirmTask)

            taskEditText.setText(taskTextView.text)

            exitButton.setOnClickListener {
                editLayout.visibility = View.GONE
                taskEditText.setText(taskTextView.text)
            }

            deleteButton.setOnClickListener {
                deleteTaskFromTasks(taskTextView.text.toString())
                loadTasks()
                editLayout.visibility = View.GONE
            }

            confirmButton.setOnClickListener {
                deleteTaskFromTasks(taskTextView.text.toString())
                addTaskToTasks(taskEditText.text.toString())
                loadTasks()
                editLayout.visibility = View.GONE
            }
        }
        taskCheckBox.setOnClickListener{
            addTaskToFinishedTask(taskTextView.text.toString())
            deleteTaskFromTasks(taskTextView.text.toString())
            loadTasks()
        }
    }

    class TaskItem(val taskText: String): Item<ViewHolder>(){
        override fun bind(viewHolder: ViewHolder, position: Int) {
            val taskTextView = viewHolder.itemView.findViewById<TextView>(R.id.taskTextView)
            val taskCheckBox = viewHolder.itemView.findViewById<CheckBox>(R.id.taskCheckBox)
            taskTextView.text = taskText
            taskCheckBox.isChecked = false
        }
        override fun getLayout(): Int {
            return R.layout.task
        }
    }

标签: android-studiokotlinandroid-recyclerview

解决方案


推荐阅读