如何随机化Android中的按钮顺序

时间:2013-04-29 10:21:54

标签: java android button

我读过关于集合的随机化对象的顺序。有了它,我想尝试在我的Android应用程序中随机化我的按钮。

这里有一大堆代码:

 Button[] bObject = new Button[6];
 private void getCorrectObject() {
    // TODO getCorrectObject

    List<Integer> objects = new ArrayList<Integer>();
        objects.add(0);
        objects.add(1);
        objects.add(2);
        objects.add(3);
        objects.add(4);

    // Shuffle the collection
    Collections.shuffle(objects);

    bObject[objects]; // I'm having trouble implementing the shuffle logic here.


}

所以任何有用的回应都是真的很感激。感谢。

4 个答案:

答案 0 :(得分:0)

第一

Button[] bObject=new Button[6];

第二

for(int i=0;i<objects.size;i++)
   bObject[i]=objects.get(i);

或:

for(Object obj : objects)
 bObject[i]=obj;

答案 1 :(得分:0)

我认为这就是你要找的东西。改组bObject数组中的元素。

Collections.shuffle(Arrays.asList(bObject));

答案 2 :(得分:0)

手动解决它,然后尝试动态解决它。有一个好主意,你可以用第二个arraylist来做。

List<Integer> objects = new ArrayList<Integer>();
            objects.add(0);
            objects.add(1);
            objects.add(2);
            objects.add(3);
            objects.add(4);

        // Shuffle the collection
    Collections.shuffle(objects);

    List<Button> buttons = new ArrayList<Button>();
    buttons.add((Button)findViewById(R.id.button0));
    buttons.add((Button)findViewById(R.id.button1));
    buttons.add((Button)findViewById(R.id.button2));
    buttons.add((Button)findViewById(R.id.button3));
    buttons.add((Button)findViewById(R.id.button4));

    for (int i = 0; i < objects.size(); i++) {
        buttons.get(i).setText(objects.get(i).toString());
    }

这对你有帮助吗?

修改 是的,让我们在聊天中解决这个问题我也很好奇如何做到这一点!

答案 3 :(得分:0)

我有同样的问题(随机播放按钮),我想出了一个简单的解决方案 我只使用了一组整数个按钮id和简单的shufle。在我的情况下就足够了。它很简单,你也得到相同的结果。

Integer[] a =  { 0x7f090049, 0x7f09004b, 0x7f09004c, 0x7f090048};
Collections.shuffle(Arrays.asList(a));

button1 = (Button)findViewById(a[0]);
button2 = (Button)findViewById(a[1]);
button3 = (Button)findViewById(a[2]);
button4 = (Button)findViewById(a[3]);

我希望这会有所帮助。 问候 !! (为我破碎的英语而烦恼)