简体   繁体   English

如何在expandable listview中保存复选框的状态 - Android

[英]How to save state of checkboxes in expandable listview - Android

I'm displaying entries from SQLite database in Expandable ListView and everything is working correctly but, I wanted to add in a checkbox right next to all children. 我在Expandable ListView中显示来自SQLite数据库的条目,一切正常但是,我想在所有孩子旁边添加一个复选框。 Every time I check a checkbox and then scroll down or contract the checkbox which I had checked it doesn't save the state of the checkbox. 每次我选中一个复选框,然后向下滚动或收缩我选中的复选框,它不会保存复选框的状态。 I know that the list is recycled whenever I scroll down and expand the groups and so forth. 我知道每当我向下滚动并展开组等时,列表就会被回收。 How can I save the state of every checkbox (by every child)? 如何保存每个复选框的状态(由每个孩子)? I have a class which extends CursorTreeAdapter and there is no "childPosition" in the methods. 我有一个扩展CursorTreeAdapter的类,方法中没有“childPosition”。 What do I need to do in order to save the state? 为了挽救国家,我需要做什么?

你可以有一个布尔标志数组,其大小与列表元素的总和相同,并设置并从该数组中获取任何组件的选中值。

One more solution is you can hold a counter for each element in list view. 还有一个解决方案是您可以为列表视图中的每个元素保留一个计数器。 For example if you have Person list, you can add one counter variable in your Person class. 例如,如果您有Person列表,则可以在Person类中添加一个计数器变量。

And in getChildView method, put all codes in an if block like below; 在getChildView方法中,将所有代码放在if块中,如下所示;

    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) {

    //FOR SAVE THE STATES!!
    if(parents.get(groupPosition).getCounter()==0) {
        DatePicker datePicker = null;
        Button ok = null;
        Spinner installment = null;
        CheckBox creditCard;
        ......//BLA BLA BLA


        //After finish your codes, increment the counter
        parents.get(groupPosition).setCounter((parents.get(groupPosition).getCounter()+1));
    }

    return convertView;
}

Because for each expandGroup method called, all the initializations (for now those are in if block) repeats. 因为对于每个调用的expandGroup方法,所有初始化(现在都在if块中)都会重复。 Because of that you loose your state of objects. 因此,你失去了对象的状态。

Hope this help. 希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM