android动态创建复选框检查检测

时间:2014-01-02 09:10:22

标签: android

我在我的应用程序中动态创建了一个复选框列表。我想检测点击了哪个复选框...请帮助 这是我的代码..

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_place_bid);
  String[] sh=item_list();
  int array_length=jArray.length();
  LinearLayout linearLayout = (LinearLayout) findViewById(R.id.lyout);

  for(int c=0; c<jArray.length();c++){
    CheckBox chk=new CheckBox(this);
    chk.setId(c+1);
    chk.setText("Click to add values");
    chk.setTextColor(Color.GRAY);
    linearLayout.addView(chk);
  }

  for(a = 1;a<=array_length;a++){
    CheckBox  satView = (CheckBox)findViewById(a);  
    satView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
        String s="x"+a;
        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();   
      }
    });
  }
}

1 个答案:

答案 0 :(得分:3)

试试这个..

  @Override
        protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_place_bid);
          String[] sh=item_list();
          int array_length=jArray.length();
          LinearLayout linearLayout = (LinearLayout) findViewById(R.id.lyout);

          for(int c=0; c<jArray.length();c++){
            CheckBox chk=new CheckBox(this);
            chk.setId(c+1);
            chk.setText("Click to add values");
            chk.setTextColor(Color.GRAY);
            chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
              @Override
              public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
               String s="x"+buttonView.getId();
               Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();

                switch(buttonView.getId()){

                  case 1: // do something on 1st checkbox
                        break;

                  case 2: //do something on 2nd  checkbox
                       break;

                //And SO ON for all checkboes
            }  
           }
          });
            linearLayout.addView(chk);
          }


        }

如果SetId(Int)无效,那么您可以改用setTag(int)getTag()