I have a radioGroup and four radiobutton, I just Want to arrange these radiobuttons randomly whenever the program is running.
Say i have radio buttons r1,r2,r3,r4 and a radiogroup. I want sometimes these radiobuttons arranged like r2,r3,r1,r4 (vertically) and some times r1,r2,r4,r3 and so on...
How can i Implement this?
For implementing random RadioButton
random sequence following code will help you:
In your layout.xml
file add RadioGroup
:
<RadioGroup
android:id="@+id/gul_radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
And in your java file:
final int NUMBER_OF_RADIOBUTTONS_TO_ADD = 4;//Change it for other number of RadioButtons
RadioButton[] radioButton;
RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = (RadioGroup) findViewById(R.id.gul_radio_group);
//Initializing the RadioButtons
radioButton = new RadioButton[NUMBER_OF_RADIOBUTTONS_TO_ADD];
for (int i = 0; i < NUMBER_OF_RADIOBUTTONS_TO_ADD; i++) {
radioButton[i] = new RadioButton(this);
//Text can be loaded here
radioButton[i].setText("Button " + (i + 1));
}
//Random Swapping
for (int i = 0; i < 4; i++) {//this loop is randomly changing values 4 times
int swap_ind1 = ((int) (Math.random() * 10) % NUMBER_OF_RADIOBUTTONS_TO_ADD);
int swap_ind2 = ((int) (Math.random() * 10) % NUMBER_OF_RADIOBUTTONS_TO_ADD);
RadioButton temp = radioButton[swap_ind1];
radioButton[swap_ind1] = radioButton[swap_ind2];
radioButton[swap_ind2] = temp;
}
radioButton[0].setChecked(true);//This will make the top RadioButton selected by default
//Adding RadioButtons in RadioGroup
for (int i = 0; i < NUMBER_OF_RADIOBUTTONS_TO_ADD; i++) {
radioGroup.addView(radioButton[i]);
}
}