Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to allow only 1 android toggle button out of 3 to be on at once

i am using 3 toggle buttons. In my android application i would like that only 1 of these toggle buttons can be selected at once. How would i go about doing this?

like image 762
molleman Avatar asked Jun 08 '11 17:06

molleman


1 Answers

A simple onChangeListener will do:

public class TestProjectActivity extends Activity {

ToggleButton one; 
ToggleButton two;
ToggleButton three;
ToggleButton four;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    one = (ToggleButton) findViewById(R.id.toggleButton1);
    two = (ToggleButton) findViewById(R.id.toggleButton2);
    three = (ToggleButton) findViewById(R.id.toggleButton3);
    four = (ToggleButton) findViewById(R.id.toggleButton4);

    one.setOnCheckedChangeListener(changeChecker);
    two.setOnCheckedChangeListener(changeChecker);
    three.setOnCheckedChangeListener(changeChecker);
    four.setOnCheckedChangeListener(changeChecker);
}

OnCheckedChangeListener changeChecker = new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked){
            if (buttonView == one) {
                two.setChecked(false);
                three.setChecked(false);
                four.setChecked(false);
            }
            if (buttonView == two) {
                one.setChecked(false);
                three.setChecked(false);
                four.setChecked(false);
            }
            if (buttonView == three) {
                two.setChecked(false);
                one.setChecked(false);
                four.setChecked(false);
            }
            if (buttonView == four) {
                two.setChecked(false);
                three.setChecked(false);
                one.setChecked(false);
            }
        }
    }
};

}

like image 173
ThePikeman Avatar answered Sep 29 '22 19:09

ThePikeman