3

整数 0,1,2,3,4 のリストがあります。次に、シャッフルします。3 番目のステップとして、button1 に関連する最初のオブジェクト、button2 に関連する 2 番目のオブジェクトなどでボタンを初期化します。手動で行うと機能しますが、動的に解決したいと考えています。

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

//this is not working here, but it should reflect what i am trying to achieve here
// -->
    for (int i = 0; i<objects.size(); i++) {
        Button button**i** = (Button)findViewById(R.id.button**i**);
        button**i**.setText(objects.get(i).toString());
    }

前もって感謝します。助けていただければ幸いです(正しい方向に鼻を突っ込んでください)

4

1 に答える 1

4

これは、ボタン リストをシャッフルすることで解決できます。int で反復しているため、シャッフルされたリストのインデックスとして機能します。

このような:

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

Collections.shuffle(buttons);

for (int i = 0, s = 4; i < s; i++) {
    buttons.get(i).setText("" + i);
}
于 2013-04-29T11:12:28.650 に答える