RadioButtons example

Erel

B4X founder
Staff member
Licensed User
Longtime User
RadioButtons are usually used to allow the user to choose a single option from multiple available options. CheckBox for example allows the user to choose multiple options.

Some code is required in order to make the RadioButtons behave as expected.
In this example we will extend RadioButton. The extended RadioButton will make sure that only a single RadioButton (grouped by the same parent) is checked.

This is our Java code:
B4X:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import anywheresoftware.d4a.Designer4android;
import anywheresoftware.d4a.OnLayoutLoadedListener;

public class Test1Activity extends Activity implements OnLayoutLoadedListener{
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Designer4android d4a = new Designer4android("1");
      ViewGroup vg = d4a.loadLayout(this, this);
      setContentView(vg);
   }
   public void onLayoutLoaded(Designer4android d4a, boolean success, Exception e) {
      if (!success) {
         Log.e("MyTag", "Error loading layout file", e);
         finish(); //close the activity
         return;
      }
   }
   
   public static class MyRadioButton extends RadioButton {

      public MyRadioButton(Context context) {
         super(context);
         setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
               if (!isChecked)
                  return;
               ViewParent vp = MyRadioButton.this.getParent();
               if (vp instanceof ViewGroup) {
                  ViewGroup vg = (ViewGroup) vp;
                  for (int i = 0;i < vg.getChildCount();i++) {
                     View v = vg.getChildAt(i);
                     if (v instanceof RadioButton) {
                        if (v != MyRadioButton.this) {
                           RadioButton rb = (RadioButton) v;
                           if (rb.isChecked())
                              rb.setChecked(false);
                        }
                     }
                  }
               }
            }
         });
      }
   }
}

Our layout is made of 3 RadioButtons placed on the Activity and 3 RadioButtons placed on a Panel.
The NativeClass is set to our extended class:

SS-2012-04-23_15.59.42.png


The runtime result:
SS-2012-04-23_15.58.24.png
 
Top