如何在android中检索选中复选框的id 字符串s; 复选框cb[]=新复选框[n]; 对于(inti=0;i

如何在android中检索选中复选框的id 字符串s; 复选框cb[]=新复选框[n]; 对于(inti=0;i,android,checkbox,Android,Checkbox,尝试使用下面的方法 String s; CheckBox cb[]= new CheckBox[n]; for(int i=0;i<n;i++) { // CheckBox String label = a[i]; cb[i]=new CheckBox(this); cb[i].setText(label); cb[i].setTextColor(Color.parseColor("#006400"));

尝试使用下面的方法

   String s;
   CheckBox cb[]= new CheckBox[n];
   for(int i=0;i<n;i++) {   
      // CheckBox
      String label = a[i];
      cb[i]=new CheckBox(this);
      cb[i].setText(label);
      cb[i].setTextColor(Color.parseColor("#006400"));
      cb[i].setId(i);
   }

  if(cb[i].isChecked()) {
      s+=i+",";
  }

稍后,您可以通过t
S.toString()
方法将其转换为字符串;

您可以使用列表并在onCreate方法之外声明字符串:

StringBuilder s = new StringBuilder();
     ---
      ----
     ----


if(cb[i].isChecked())
  {
       s.append(i+",");
    }
私有字符串s;
创建时的公共无效{
最终列表映射=新的ArrayList();
复选框[]ch=。。。;

对于(int i=0;i)您的代码不完整且缩进严重。您能更新它以方便阅读吗?我不觉得需要整个代码块,只提供了重要的代码。这与我的代码所做的工作几乎相同,我不理解的是何时使用isChecked()在循环创建按钮之后,它能工作吗?我也尝试过这种方法,唯一的问题是我可以从中获得按钮本身的id或参数。但是我想做的是获得id,然后附加名称[id]在字符串中,其中name是一个字符串数组,我不能将其声明为final。ide给了我一个错误,即无法在中访问非final变量。。。。。。。。
private String s;

public void onCreate... {
    final List<Integer> map = new ArrayList<Integer>();
    CheckBox[] ch = ...;
    for(int i=0;i<ch.length;i++) {
    ch[i].setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked) {
                map.add(buttonView.getId());
            } else {
                map.remove(buttonView.getId());
            }
            s = "";
            for (Integer i : map) {
                s += i+",";
            }
        }
    });
}