android - 从多选 ListView 返回值

标签 android listview multiple-select

编辑:好的,我找到了解决方案。不知道这是正确的解决方案,但它确实可以正常工作。添加到下面的代码中。

我试图让用户从 list 中选择多个目录,并在单击“提交”按钮后返回它们。这是我的代码 fragment 。它使用/sdcard/上的所有目录填充 ListView,并且对于提交时的初始选择(无论我选择多少),日志显示返回的正确选择。但是,如果我取消选中一个项目,然后再次单击“提交”,它仍然显示为好像所有都被选中了。我是否需要编写一个处理程序来取消选中某个项目?我认为这是由 choiceMode 选择解决的?谢谢!

private SparseBooleanArray a;    
directoryList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, directoryArray));
    submitButton = (Button)findViewById(R.id.submit_button);
    submitButton.setOnClickListener(new OnClickListener()
        {
        @Override
        public void onClick(View v)
        {
            a = new SparseBooleanArray();
            a.clear();
            a = directoryList.getCheckedItemPositions();

            for (int i = 0; i < a.size(); i++)
            {
                //added if statement to check for true. The SparseBooleanArray
                //seems to maintain the keys for the checked items, but it sets
                //the value to false. Adding a boolean check returns the correct result.                    
                if(a.valueAt(i) == true)
                    Log.v("Returned ", directoryArray[a.keyAt(i)]);

            }                
        }
    });

最佳答案

进行了更多调试并找到了适合我的解决方案。编辑成上面的代码。出于某种原因,SparseBooleanArray 不会自行清空;它维护已选中的框的键。但是,当调用 getCheckedItemPositions() 时,它将 VALUE 设置为 false。所以键仍在返回的数组中,但它的值为 false。只有选中的框会被标记为 true。

关于android - 从多选 ListView 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3464636/

相关文章:

android - Google Places api for android 网络错误

android - 自定义全息样式进度条

java - Android gridview 不维护元素顺序(除非牺牲性能)

android - ListView 中的 TextView : the text overflowing the screen

react 原生多选 : Cannot read the property 'getSelectedItemsExt' of undefined

java - 从网页获取数据并在Android Java上使用

wpf - ListView XAML 中的替代背景颜色

android改变listview的字体和颜色

PHP ( Wordpress) - 选择多个 - 显示 "selected"状态不工作

jquery - jquery页面上的多个依赖选择框