ExpandableListView без дочерних элементов выдает исключение indexOutOfBoundsException - PullRequest
0 голосов
/ 20 июня 2020

У меня есть ExpandableListView, где у некоторых групп есть дети, а у некоторых нет, мне нужно расширить только те группы, у которых есть дети.

Часть элементов массива body пуста и из-за этого я получаю IndexOutOfBoundsException

    class ExpandableInnerCartAdapter(
        var context: Context,
        var expandableListView: ExpandableListView,
        var header: MutableList<Cart>,
        val isTerminadoFragment:Boolean
    ) : BaseExpandableListAdapter() {
    
        val map = SparseBooleanArray()
        var body: List<List<String>> = listOf()
    
        override fun getGroup(groupPosition: Int): Cart {
           return header[groupPosition]
        }
    
        override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {
           return true
        }
    
        override fun hasStableIds(): Boolean {
            return false
        }
    
        fun getCart(): MutableList<Cart> = header
        fun getCheckedArray():SparseBooleanArray = map
    
        override fun getGroupView(
            groupPosition: Int,
            isExpanded: Boolean,
            convertView: View?,
            parent: ViewGroup?
        ): View {
    
            var convertView = convertView
            if(convertView == null){
                val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
                convertView = inflater.inflate(R.layout.layout_group,null)
            }
            val item = header[groupPosition]
            body = listOf(item.optionList)
            expandableListView.expandGroup(groupPosition)
            expandableListView.setGroupIndicator(null)
            convertView.item_name.text = item.productName
           
            return convertView
    
        }
    
        override fun getChildrenCount(groupPosition: Int): Int {
            return body[groupPosition].size
        }
    
        override fun getChild(groupPosition: Int, childPosition: Int): Any {
            return body[groupPosition][childPosition]
        }
    
        override fun getGroupId(groupPosition: Int): Long {
            return groupPosition.toLong()
        }
    
        override fun getChildView(
            groupPosition: Int,
            childPosition: Int,
            isLastChild: Boolean,
            convertView: View?,
            parent: ViewGroup?
        ): View {
            var convertView = convertView
            if(convertView == null){
                val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
                convertView = inflater.inflate(R.layout.layout_child,null)
            }
            if(getChildrenCount(groupPosition) > 0){
                val title = convertView?.findViewById<TextView>(R.id.tv_title)
                title?.text = "Opción ${childPosition+1} -> ${getChild(groupPosition,childPosition)}"
            }
    
            return convertView!!
        }
    
        override fun getChildId(groupPosition: Int, childPosition: Int): Long {
            return childPosition.toLong()
        }
    
        override fun getGroupCount(): Int {
            return header.size
        }
    }

Кажется, что ошибка происходит, когда ни у одной группы нет детей, и я пытаюсь сделать

    expandableListView.expandGroup(groupPosition)

Я пытался исправить проблема с оператором if:

    if(body.isNotEmpty()){
        expandableListView.expandGroup(groupPosition)
    }

, но это решение не работает.

Как избежать групп, у которых нет детей?

Спасибо

1 Ответ

1 голос
/ 20 июня 2020

Поскольку вы используете Kotlin, в вашем распоряжении множество полезных функций расширения. Один из них - filter, для которого вы, конечно, можете указать условие.

Решением было бы отфильтровать пустые массивы из списка, который вы установили как новое body значение:

    body = listOf(item.optionList).filter { it.isNotEmpty() }

Определение функции фильтра можно увидеть здесь .

...