how to randomize the order of buttons in Android

2019-04-17 12:46发布

I've read about collections to randomize the order of an object. With that, I'd like to try to randomize my buttons in my android application.

Here a chunk of code:

 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.


}

SO any helpful response is truly appreciated. Thanks.

4条回答
Bombasti
2楼-- · 2019-04-17 13:19

first

Button[] bObject=new Button[6];

second:

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

or:

for(Object obj : objects)
 bObject[i]=obj;
查看更多
Deceive 欺骗
3楼-- · 2019-04-17 13:23

I think this is what you're looking for. Shuffling the elements in the bObject array.

Collections.shuffle(Arrays.asList(bObject));
查看更多
Lonely孤独者°
4楼-- · 2019-04-17 13:35

I had a same problem (shuffle buttons) and i come up with an easy solution I just used an array of integer numbers of buttons ids and simple shufle. In my case was that enough. It's simple and u get the same result.

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]);

I hope this will help. Regards !! (srry for my broken english)

查看更多
We Are One
5楼-- · 2019-04-17 13:37

got it solved manually and then tried to get it solved dynamically aswell. got a nice idea that you can do it with a second 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());
    }

does this help you?

EDIT: yes let us solve this in chat. im also curious how this can be done!

查看更多
登录 后发表回答