I got one RadioGroup with four Radios.
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
RadioButton r0 = (RadioButton) findViewById(R.id.radio0);
RadioButton r1 = (RadioButton) findViewById(R.id.radio1);
RadioButton r2 = (RadioButton) findViewById(R.id.radio2);
RadioButton r3 = (RadioButton) findViewById(R.id.radio3);
I set the text to all of them.
r0.setText("1");
r1.setText("2");
r2.setText("3");
r3.setText("4");
So i got that radios like this 1, 2, 3, 4. How can I randomly swap positions of radios. I want to get something like this 3,2,1,4 or 2,3,1,4....etc... But IMPORTANT I don't want to change text of radios, as I said I want positions to be swapped.
I don't think you can achieve this using the same layout XML file.
Use 4 different layouts, and inflate it randomly.
All your IDs will always work if you keep the same in each XML file.
@Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
setContentView(randomLayout());
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
// ...
}
public static int randomLayout() {
final int n[] = { R.layout.layout1, R.layout.layout2, R.layout.layout3, R.layout.layout4 }
Random random = new Random();
return n[random.nextInt(n.length)];
}
very quickely : if you don't have any idea, try something on this way
something like...
int n = nb of radios;
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
RadioButton r0 = new RadioButton(this);
RadioButton r1 = new RadioButton(this);
RadioButton rn = new RadioButton(this);
r0.setId(/*idr0*/);
r1.setId(/*idr1*/);
rn.setId(/*idrn*/);
r0.setText("text0");
rn.setText("textn");
ArrayList<RadioButton> e = new ArrayList<RadioButton>();
e.add(r0);
e.add(rn);
Random rand = new Random();
while(n<0)
{
int i = rand.nextInt(n);
if (e.get(i) != null)
{
rg.add(e.get(i));
e.remove(i);
n--;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.