How to allow only one Android toggle button of 3 at a time

I use 3 toggle buttons. In my Android app, I would like only one of these toggle buttons to be selected right away. How can I do it?

+6
source share
4 answers

You can use radio buttons . If you do not want this, check out this link - it shows you how to listen to the state changes of the button. If you find that one of your buttons is changed, change the other 2 to the off state.

+3
source

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); } } } }; 

}

+11
source

ThePikeman's solution is fine, but depending on how many buttons you have, you might want to consider an array that you can iterate over.

For a small number of buttons, the Pikeman code can be simplified to preserve some typing ...

 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ if (buttonView != one) { one.setChecked(false); } if (buttonView != two) { two.setChecked(false); } if (buttonView != three) { three.setChecked(false); } if (buttonView != four) { four.setChecked(false); } } } 
+4
source

I am using the following function:

 private void setIsChecked(CheckBox checkBox){ buttonOne.setChecked(false); buttonTwo.setChecked(false); buttonThree.setChecked(false); checkBox.setChecked(true) } 

now all of them are counted except the one you choose

ex

 setIsChecked(buttonOne); 

Now only one button is checked, etc.

0
source

Source: https://habr.com/ru/post/890079/


All Articles