【问题标题】:Method that scans through chekboxes in a listview在列表视图中扫描复选框的方法
【发布时间】:2014-01-13 16:01:23
【问题描述】:

我正在试验这个示例项目:http://schimpf.es/listview-with-checkboxes-inside/

我在包含 ListView 的 xml 文件中添加了一个按钮。 当它被按下时,我想要一种方法来扫描复选框数组并检查它们是否都被选中。

有人可以帮帮我吗?

【问题讨论】:

  • 请添加一些代码来帮助我们帮助您。

标签: java android listview checkbox android-checkbox


【解决方案1】:

试试这个:

private boolean checkBoxes(){
  for(SampleData s : dataList) if (s.selected == false) return false;
  return true;
}

【讨论】:

    【解决方案2】:

    我无法让它工作。 它总是返回 false。

    我把方法放到CheckBoxListAdapter.java中

    public boolean allChecked() {
        for (Object item : dataList) {
            if (!((SampleData) item).isSelected())
                return false;
        }
        return true;
    }
    

    在我的 MainActivity 中,我在按钮 onClick 时调用该方法。然后我得到它的价值。

    public void onClickNeste_sjekkliste (View v) {
        CheckboxListAdapter test = new CheckboxListAdapter(null);
        test.allChecked();
        boolean ifCheckedAll = test.allChecked();
    
        if (ifCheckedAll == false) {
            Log.d("CheckedAll", "false");
        }
        else if (ifCheckedAll == true) {
            Log.d("CheckedAll", "true");
        }   
    }
    

    【讨论】:

    • 这是因为您正在扫描一个名为“test”的全新适配器,而不是在连接到 ListView 的 onCreate 中设置的适配器。 CheckBoxListAdpater 的初始状态是真假混合,因此你总是得到假。您需要在“适配器”上调用该方法。请查看我的更新答案。
    【解决方案3】:

    遍历 dataList 中的每个条目。如果你得到一个没有设置的,返回 false。如果他们都通过了测试,则返回 true:

    private boolean allChecked()
    {
        for(Object item : dataList)
        {
            if (!(SampleData)item.isSelected())
                return false;
        }
        return true;
    }
    

    请注意,dataList 被定义为 Object 类型的 ArrayList,而不是 SampleData 类型。因此,当您迭代每个条目时,需要将其强制转换为 SampleData。

    编辑:

    要使用它,请更改 Activity 类,使 'adapter' 成为类变量:

    public class CheckboxListActivity extends ListActivity {
    
        //Define adapter here so that you can refer to it anywhere within the Activity
        CheckboxListAdapter adapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_checkbox);
    
            //Set the class level 'adapter' variable
            adapter = new CheckboxListAdapter(getLayoutInflater());
            getListView().setAdapter(adapter);
        }
    }
    

    在您的 onClick 中,对变量“适配器”调用新方法:

    public void onClickNeste_sjekkliste (View v) {
        boolean ifCheckedAll = adapter.allChecked();
    
        if (ifCheckedAll == false) {
            Log.d("CheckedAll", "false");
        }
        else if (ifCheckedAll == true) {
            Log.d("CheckedAll", "true");
        }   
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多