【问题标题】:How to randomize(or shuffle) order of Radio Buttons如何随机化(或打乱)单选按钮的顺序
【发布时间】:2019-04-11 03:21:55
【问题描述】:

我想在重新打开应用时随机化我的单选按钮。

例如我的布局如下:

RBtn1
Rbtn2
Rbtn3
Rbtn4

现在我想在打开该特定活动时对它们进行随机播放。我该怎么做?

【问题讨论】:

  • 您只想编辑他们的名字或他们的功能?
  • 你能分享你的代码吗?
  • 您好,我会根据我对它的了解尝试回答您的问题。但是下次尝试放置更多有用的信息,例如您的整个布局文件或如何创建视图。

标签: java android radio-button radio-group


【解决方案1】:

据我所知,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)
    }

    }

}

我认为它应该可以工作,否则评论框就在那里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多