【问题标题】:Android adding and removing to a different ListView using ArrayListAndroid使用ArrayList添加和删除到不同的ListView
【发布时间】:2014-07-27 00:00:40
【问题描述】:

这让我发疯了。我有一个ListView 和一个ArrayList 作为我的适配器。 ListView 模式为CHOICE_MODE_MULTIPLE,布局为simple_list_item_checked。我现在可以在我的ListView 中选择多个项目。

我的情况:

    int length = jsonList.size();

    SparseBooleanArray checked = lv_Devices.getCheckedItemPositions();

    for (int i = 0; i <length ; i++ ){

         if (checked.get(i)) {


             onList.add(jsonList.get(i));

             jsonList.remove(i);
             lv_Devices.setItemChecked(i, false);


             length--;

        }   
    }
    adapter.notifyDataSetChanged();
    adapterOn.notifyDataSetChanged();

这里是 LogCat:

size of array 8 : contains [1, 2, 3, 4, 5, 6, 7, 8]  

you removed index 0  
[2, 3, 4, 5, 6, 7, 8]  


you removed index 1  
[2, 4, 5, 6, 7, 8]  


you removed index 2  
[2, 4, 6, 7, 8]  


you removed index 3  
[2, 4, 6, 8]  

从最终结果可以看出,数组正在移动索引。我试图实现的目标:获取每个选定的项目并将它们添加到另一个 ListView,同时从当前的 ListView 中删除。

LogCat 显示当我选择所有项目时会发生什么。这也发生在单击按钮时。对此的任何建议都是完美的。这也是我第一次使用stackoverflow。我并没有真正使用它,因为这里已经讨论了大多数编程错误。我在这个问题上遇到了困难。

【问题讨论】:

    标签: java android listview android-listview arraylist


    【解决方案1】:

    试试这样的:

    int item = 0;
    
    for (int i = 0; i < length; i++) {
    
        if (checked.get(i)) {
            onList.add(jsonList.get(item));
            jsonList.remove(item);
            lv_Devices.setItemChecked(i, false);
        }
        else {
            item++;
        }
    }
    

    它将尝试删除数组中的第一项(第 0 项)。如果该项目被选中,它将被删除。这意味着以前是项目 1 的项目现在是项目 0,所以它会再次检查项目 0。

    但是,如果第 0 项没有被选中,它会移动到第 1 项,并继续做同样的事情。

    【讨论】:

    • 非常感谢您的回复。我刚刚试了一下,现在它移动 1 , 3 , 5 , 7 并跳过 2 , 4 , 6 , 8
    • @Rachel 勾选了哪些项目?
    • 所有这些=S这就是为什么我这么困惑
    • 另外,如果这有帮助,如果我只选择要移动的 1 和 2,它会移动 1 和 3
    • 我想我意识到我做了什么——我刚刚更新了代码。你能帮我试试,让我知道它是否有效?
    猜你喜欢
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多