【问题标题】:selected check boxes count and passing it to another activity选中的复选框计数并将其传递给另一个活动
【发布时间】:2014-05-15 01:17:51
【问题描述】:

我在第一个活动中有 4 个复选框,我只想存储那些用户选择的复选框,并且必须在另一个活动中显示我的问题是我如何计算用户选择的复选框。请帮我讲逻辑

int x = 0;

public void onCheckboxClicked(View view) {
    checked = ((CheckBox) view).isChecked();
    if (((CheckBox) view).isChecked() == true) {
        int i = 0;
        while (i != 4) {
            x = i + 1;
            i++;
        }
    }
}

在提交按钮上

    if(x!=0) {
      show alert();
      and passing check boxes selected count 
}

【问题讨论】:

  • 在选定条件下 x 的值始终为 4。请说明您的登录信息
  • 为什么只提交被勾选的复选框数量而不提交哪些复选框?

标签: android checkbox arraylist


【解决方案1】:

您可以运行一个循环并找到 CheckBox 视图的数量,然后相应地获取已选中 CheckBox 的计数

例如:

main = (LinearLayout) findViewById(R.id.main);
    btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    count = 0;
                    int childcount = main.getChildCount();
                    for (int i=0; i < childcount; i++){
                          View view = main.getChildAt(i);
                          if (view instanceof CheckBox) {
                              if(((CheckBox) view).isChecked())
                                  count++;
                          }
                    }
                    text.setText("count: " + count);
                }
            });

【讨论】:

  • XML 中有多少复选框并不重要。 count 的结果将是“选中”复选框的数量
【解决方案2】:

首先将复选框放入数组中:

ArrayList<CheckBox> checkList = new ArrayList<CheckBox>();

你可以这样做:

for(int i=0 ; i<4; i++)
{
   checkList.add(YOURCHECKBOX) ;
}

您可以检查哪些 CB 已检查(实现您希望它仅保存已检查的那些..):

for(int i=0 ; i<checkList.size(); i++)
{
    if(checkList.get(i).isChecked() == true)
      {
        YOURCODE
      }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多