I want to randomize my radio buttons whenever I reopen my app.
For example my layout is like below:
RBtn1
Rbtn2
Rbtn3
Rbtn4
Now I want to shuffle them whenever I open that particular activity. How can I do this?
I want to randomize my radio buttons whenever I reopen my app.
For example my layout is like below:
RBtn1
Rbtn2
Rbtn3
Rbtn4
Now I want to shuffle them whenever I open that particular activity. How can I do this?
As far I know, Layouts
in resources
are immutable. That means you've to make Views
in the dynamic or Java way.
What you can do is use the SecureRandom class (accurate than Random for picking random numbers) to pick a random number and take one RadioButton object from the RadioButton array what you will create.
PoC: I'm explaining first by a now written and tested code →
import java.util.*;
public class HelloWorld{
static String los1 = "taotao1";
static String los2 = "taotao2";
static String los3 = "taotao3";
static String los4 = "taotao4";
static String[] X = {los1,los2,los3,los4};
public static void main(String []args){
Collections.shuffle(Arrays.asList(X));
System.out.println(Arrays.toString(X));
}
/*
Test 1 : [taotao4, taotao3, taotao2, taotao1]
Test 2 : [taotao2, taotao3, taotao4, taotao1]
Test 3 : [taotao3, taotao4, taotao1, taotao2]
Test 4 : [taotao2, taotao4, taotao1, taotao3]
*/
}
Explanation: Collections.shuffle
shuffles objects in an Array as you will be able to see by running code.
Conceptual Code: I'm saying it conceptual because writing directly in Stack Answer Box without testing, Test to be done by you.
public class NoNotHelloWorld extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
RadioButton r1,r2,r3,r4; //please declare to avoid NullPtr and also declare their functionalities
LinearLayout xyz = (LinearLayout)findViewById(R.id.xyzwhatisthis);
//though unnesseary cast, but I did it.
ArrayList<RadioButton> dydx = new ArrayList<RadioButton>();
dydx.add(r1);
dydx.add(r2);
dydx.add(r3);
dydx.add(r4);
Collections.shuffle(Arrays.asList(arr));
for(RadioButton dxdy : dydx){
xyz.addView(dxdy)
}
}
}
I think it should work otherwise comment box is there.