[英]Swap positions of Radios - Android java
我得到了一个带有四个收音机的RadioGroup。
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);
我将文本设置为所有这些。
r0.setText("1");
r1.setText("2");
r2.setText("3");
r3.setText("4");
所以我得到了像这样的1、2、3、4收音机。我如何随机调换收音机的位置。 我想得到像这样的3,2,1,4或2,3,1,4 ....等...但是重要的是,我不想更改收音机的文本,因为我说过我想要位置被交换。
我认为您无法使用相同的布局XML文件来实现此目的。
使用4种不同的布局,并随机对其进行充气。
如果您在每个XML文件中都使用相同的ID,那么所有ID都将始终有效。
@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)];
}
很快:如果您不知道,请尝试这种方式
就像是...
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--;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.