I am using a RecyclerView in a Fragment to display a list of elements, each containing a checkbox, as shown below.
Upon clicking the START
button, I want to disable all of the elements in the RecyclerView.
Here is my code to do so:
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
}
}
This code disables most of the elements in recyclerView
, but for some reason it skips some, often multiple at a time. It also appears to skip subviews in a pattern that varies based on how far down the list I have scrolled.
Why is it behaving so strangely?
CodePudding user response:
A RecyclerView has an Adapter. Its job is to handle the layout of each item of the RecyclerView. This includes disabling an item.
Add a class parameter to your adapter:
private var disabled = false
Add a method to your Adapter:
fun setDisabled(disabled: Boolean) {
this.disabled = disabled
notifyDatasetChanged()
}
In your onBindViewHolder method, check for the disabled parameter and disable the view as you want to:
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)
}
}
Now call setDisabled(true) on a button click:
startButton.setOnClickListener {
// yes, recyclerView is defined
adapter.setDisabled(true)
}
And call setDisabled(false) to enable the items back.