Toggle button with radio button behaviour

1.4k Views Asked by At

I have a set of toggle buttons in a relative layout.

A user should be able to select only one toggle button at a time.

I have tried the following link but none of them seem to work.

Any idea on how this can be achieved?

2

There are 2 best solutions below

0
On

It's not working probably because of all RadioButtons are not grouped together because of some View between them.

RadioButton should be the direct child of RadioGroup, Otherwise grouping does not work.

2
On

A user should be able to select only one toggle button at a time.

The code available in selected answer at your given link is doing the same job. To visualize this, change some code.

In XML

In ToggleButton, change android:textOn and android:textOff to 'on' and 'off' (Just for example). Your XML file should look like this:

<RadioGroup android:id="@+id/toggleGroup"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="24dp"
    android:orientation="horizontal"
    >

    <ToggleButton android:id="@+id/btn1"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        android:textSize="14sp"
        android:textOn="on"
        android:textOff="off"
        android:onClick="onToggle"
        android:checked="true"
        />
    <ToggleButton android:id="@+id/btn2"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        android:textSize="14sp"
        android:textOn="on"
        android:textOff="off"
        android:checked="false"
        android:onClick="onToggle"
        />
</RadioGroup>

This should look like this:

Screenshot1

In Java file

In your activity, write this code:

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

    ((RadioGroup) findViewById(R.id.toggleGroup)).setOnCheckedChangeListener(ToggleListener);
}

static final RadioGroup.OnCheckedChangeListener ToggleListener = new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(final RadioGroup radioGroup, final int i) {
        for (int j = 0; j < radioGroup.getChildCount(); j++) {
            final ToggleButton view = (ToggleButton) radioGroup.getChildAt(j);
            view.setChecked(view.getId() == i);
        }
    }
};

public void onToggle(View view) {
    ((RadioGroup)view.getParent()).check(view.getId());
    // write your specific code here ..
    Toast.makeText(this, "Toggle button clicked", Toast.LENGTH_SHORT).show();
}

When you click 'off' while another (toggle button) is 'on', 'off' will change to 'on' and vice versa. So user is able to select only one toggle button at a time. If one toggle button is on, other will always be off.