我在 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,但由于某種原因它跳過了一些,通常一次跳過多個。它似乎也以一種模式跳過子視圖,該模式根據我滾動串列的程度而有所不同。
為什么它的行為如此奇怪?
uj5u.com熱心網友回復:
RecyclerView 有一個配接器。它的作業是處理 RecyclerView 的每一項的布局。這包括禁用專案。
將類引數添加到您的配接器:
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)來啟用這些專案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/324311.html
標籤:安卓 安卓工作室 android-fragments android-recyclerview
上一篇:從非Fragment/Activity類呼叫registerForActivityResult
下一篇:標簽布局不顯示片段
