lundi 21 novembre 2016

Android looping through checkbox and togglebutton pairs

I have 20 checkbox and togglebutton pairs (cb1, tb1, cb2, tb2,....., cb20, tb20).After clicking one of the controls, I'd like to check to see if both controls in the pair are checked and act accordingly.The following onCreate code is way to cumbersome:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ck1 = (CheckBox) findViewById(R.id.ck1);
    ck2 = (CheckBox) findViewById(R.id.ck2);
    tb1 = (ToggleButton) findViewById(R.id.tb1);
    tb2 = (ToggleButton) findViewById(R.id.tb2);

    ck1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (ck1.isChecked() & tb1.isChecked())  {
                //DO SOMETHING
            };
        }
    });

    ck2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (ck2.isChecked() & tb2.isChecked())  {
                //DO SOMETHING
            };
        }
    });

    tb1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (ck1.isChecked() & tb1.isChecked())  {
                //DO SOMETHING
            };
        }
    });

    tb2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (ck2.isChecked() & tb2.isChecked())  {
                //DO SOMETHING
            };
        }
    });
    //etc.etc.etc.
}

How can I simplify to "loop" through the 20 pairs?




Aucun commentaire:

Enregistrer un commentaire