0

プログラムで 5 (5) ボタンの ID を設定し、毎回シャッフルしようとしています。
シャッフルも問題ありません。

シャッフルして 5 つのボタンの ID を設定し、それぞれのテキストを設定する 2 つのメソッドを使用すると、エラーが発生します。
for-each ループを試すのは初めてなので、これが混乱する可能性があることはわかっています。
助けてください。ありがとうございました。

Button b1, b2, b3, b4, b5;
Button[] buttons = { b1, b2, b3, b4, b5 };

    public void shuffleButtons() {

            Integer[] Id = { R.id.bChoice1, R.id.bChoice2, R.id.bChoice3,
                    R.id.bChoice4, R.id.bChoice5 };

            ArrayList<Integer> buttonId = new ArrayList<Integer>(Arrays.asList(Id));

            Collections.shuffle(buttonId);


                for (int x = 0; x < 5; x++) {

                    for (Button b : buttons) {

                        b = (Button) findViewById(buttonId.get(x));

                    }

                }


        }

public void setButtonTxt() {


            for (Button b : buttons) {

                for (int x = 0; x <= buttons.length; x++) {

                    b.setText(textList.get(x));

                }
            }

    }
4

3 に答える 3

2

プログラムで 5 (5) ボタンの ID を設定し、毎回シャッフルしようとしています。シャッフルも問題ありません。

私の提案は、すべきではない、してはいけないということです。各IDはから作成する必要があり、それぞれが静的intフィールドとしてXML自動生成されます。R.java

このルールを尊重し、「スパゲッティ コード」を作成しないでください。

于 2013-02-18T20:18:41.117 に答える
0

要するに、あなたの問題はfor ループにあるx <= buttons.lengthはずだと思います。ただし、現在のコードでx < buttons.length5 つのボタンすべてを に設定しようとしているようです。textList.get(5)

XML のプリセット ボタンを試してみませんか?

<Button android:id="@+id/bChoice1" ... />
<!-- etc -->
<Button android:id="@+id/bChoice5" ... />

次に、コードビハインドで、両方ではなくテキストをランダム化しますか?

Button b1 = (Button)findViewById(R.id.bChoice1);
Button b2 = (Button)findViewById(R.id.bChoice2);
Button b3 = (Button)findViewById(R.id.bChoice3);
Button b4 = (Button)findViewById(R.id.bChoice4);
Button b5 = (Button)findViewById(R.id.bChoice5);

// assuming textList is an ArrayList of text items
// the next two lines will randomize your textList order
// so you don't need to do it yourself and much less
// error-prone
long seed = System.nanoTime();
Collections.shuffle(textList, new Random(seed));

b1.setText(textList.get(0));
b2.setText(textList.get(1));
b3.setText(textList.get(2));
b4.setText(textList.get(3));
b5.setText(textList.get(4));
于 2013-02-18T20:29:16.307 に答える