mercredi 30 octobre 2019

Android: Generate n number of checkboxes and make 2 of them selectable

I need to make n number of checkboxes and make two of them selectable. The user can select one, then another. If the user selects a third, the second checkbox is un checked and so on. The user may also uncheck a checked box to make another choice.

I am pretty lost on what to do.

My current code: Im adding the checkboxes dynamically to a linear layout called checkBoxContainer here

 for (int i = 0; i < count; i++) {
            MaterialCheckBox checkBox = new MaterialCheckBox(context);
            checkBox.setText(String.format(Locale.getDefault(),"Checkbox %d", i));
            checkBox.setId(i);
            checkBox.setTag("Answer id : " + i);
            checkBox.setOnClickListener(this);
            checkBoxContainer.addView(checkBox);
 }

Im stuck with this part

 @Override
    public void onClick(View view) {
        int id = view.getId();
        MaterialCheckBox CheckedCheckBox = findViewById(id);
        CheckedCheckBox.setChecked(true);
        checkCount+=1;
        mLog.i(TAG,"count : + "+checkCount);
        if(checkCount<2){
        checkedIds.add(id);
        }else{
            MaterialCheckBox LastCheckedCheckBox = findViewById(id);
            LastCheckedCheckBox.setChecked(false);
            //checkedIds.remove(id)
        }


    }

You may ignore what I've written after CheckedCheckBox.setChecked(true); its just there to show that I have tired. It's nowhere near complete. Can someone give me and idea how to do this.




Aucun commentaire:

Enregistrer un commentaire