簡體   English   中英

當父代在Android中折疊時,如何更改可擴展列表視圖子代的視圖?

[英]How to change view of expandable list view children when parent is collapsed in Android?

我正在ExpandableListView實現選擇模式。 單擊孩子時,選擇會切換。 我在每個父級中都有一個CheckBox ,我想從中立即控制所有子級的選擇。

我的問題是,當父項折疊並單擊其CheckBox ,該應用程序由於空指針異常而崩潰,因為當我嘗試更改子項的選擇時,我找不到子項並獲得空值。 但是當父級擴展時,一切正常。

那么,解決此類問題的好方法是什么?

我通過添加一些代碼行而不更改先前的代碼來解決,因此此答案對於不想用其他方法重寫代碼的人可能會有所幫助。

在正在設置Adapter的調用FragmentActivity中,添加:

private val isMyGroupExpanded = SparseBooleanArray()
val MyAdapterEV = AdapterEV(/* params */) { isChecked, groupPosition ->
    changeSelection(isChecked, groupPosition)
}
// record which groups are expanded and which are not
MyAdapterEV.setOnGroupExpandListener { i -> isMyGroupExpanded.put(i, true) }
MyAdapterEV.setOnGroupCollapseListener { i -> isMyGroupExpanded.put(i, false) }
// and where changing the selection of child
private fun changeSelection(isChecked: Boolean, groupPosition: Int) {
    if (isMyGroupExpanded.get(groupPosition, false)) { 
        /* change only if the group is expanded */ 
    }
}

因此,折疊組的子級不受影響,但是在組擴展時需要更改它們,為此,在Adapter添加一些代碼行:

private val isGroupChecked = SparseBooleanArray()
// inside override fun getGroupView(...
MyCheckBoxView.setOnCheckedChangeListener { _, isChecked ->
    onCheckedChangeListener(isChecked, groupPosition)
    isGroupChecked.put(groupPosition, isChecked)
}
// inside override fun getChildView(...
if (isGroupChecked.contains(groupPosition)) {
    myView.visibility = if (isGroupChecked.get(groupPosition)) View.VISIBLE else View.INVISIBLE
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM