据我所知,resources 中的Layouts 是不可变的。这意味着您必须以动态或 Java 方式创建 Views。
您可以做的是使用 SecureRandom 类(比 Random 更准确地选择随机数)来选择一个随机数并从您将创建的 RadioButton 数组中获取一个 RadioButton 对象。
PoC:我首先通过现在编写和测试的代码来解释 →
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]
*/
}
解释:Collections.shuffle 将 Array 中的对象打乱,您可以通过运行代码看到。
概念代码:我说它是概念性的,因为直接在 Stack Answer Box 中编写,无需测试,测试由您完成。
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)
}
}
}
我认为它应该可以工作,否则评论框就在那里。