禁用 RecyclerView 的所有子视图

Disable all subviews of RecyclerView

我在 Fragment 中使用 RecyclerView 来显示元素列表,每个元素都包含一个复选框,如下所示。

单击 START 按钮后,我想禁用 RecyclerView 中的所有元素。

这是我的代码:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    startButton = view.findViewById<Button>(R.id.start_button)
    startButton.setOnClickListener {
        // yes, recyclerView is defined
        setViewGroupEnabled(recyclerView, false)
    }
}

fun setViewGroupEnabled(view: ViewGroup, enabled: Boolean) {
    Log.d(TAG, "Numkids: ${view.childCount}")
    view.isEnabled = enabled
    for (v in view.children) {
        if (v is ViewGroup) setViewGroupEnabled(v, enabled)
        else v.isEnabled = enabled
    }
}

此代码禁用了 recyclerView 中的 大多数 元素,但由于某种原因它会跳过一些元素,通常一次会跳过多个元素。它还似乎以一种模式跳过子视图,该模式根据我向下滚动列表的距离而变化。

为什么它的行为如此奇怪?

RecyclerView 有一个适配器。它的工作是处理 RecyclerView 的每个项目的布局。这包括禁用项目。

向您的适配器添加一个 class 参数:

private var disabled = false

向您的适配器添加方法:

fun setDisabled(disabled: Boolean) {
    this.disabled = disabled
    notifyDatasetChanged()
}

在您的 onBindViewHolder 方法中,检查 disabled 参数并根据需要禁用视图:

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

    if (this.disabled) {
        //disable you view, by disabling whichever subview you want
    } else {
        // The normal non disabled flow (what you have now)
    }
}

现在在单击按钮时调用 setDisabled(true)

startButton.setOnClickListener {
    // yes, recyclerView is defined
    adapter.setDisabled(true)
}

并调用 setDisabled(false) 以启用项目。