如何随机化(或随机播放)单选按钮的顺序

时间:2018-11-07 16:34:06

标签: java android radio-button radio-group

每当我重新打开应用程序时,我都希望将单选按钮随机化。

例如,我的布局如下:

RBtn1
Rbtn2
Rbtn3
Rbtn4

现在,我想在每次打开特定活动时都将它们洗牌。我该怎么办?

1 个答案:

答案 0 :(得分:0)

据我所知,Layouts中的resources是不可变的。这意味着您必须以动态或Java方式制作Views

您可以做的是使用SecureRandom类(比选择随机数更准确的随机性)来选择一个随机数,然后从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将数组中的对象随机播放,您可以通过运行代码来查看。

概念代码:我说的是概念性的,因为无需测试即可直接在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)
    }

    }

}

我认为它应该可以正常工作,否则在其中会有注释框。

相关问题