1

Android でボタンの配列を作成する方法がわかりません。

これは私が試したコードですが、java.lang.NullPointerException が発生しています。

    private Button[] button = {(Button) findViewById(R.id.cGuess1),
        (Button) findViewById(R.id.cGuess2),(Button)
        findViewById(R.id.cGuess3),(Button) findViewById(R.id.cGuess4)};

これは可能ですか?

編集:

ごめんなさい。間違いに気づきました!

クラス全体の配列を宣言しようとしていて、onCreate の前に ID からビューを取得しようとしていたため、setContentView(R.layout.game); はありませんでした。

ごめん。

4

5 に答える 5

2

他の誰もソリューションの実際のコードを投稿していないので、ここに実際のコードを示します。

Button[] myButtons = null;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    myButtons = new Button[]
    {
            (Button)findViewById(R.id.button1),
            (Button)findViewById(R.id.button2),
            (Button)findViewById(R.id.button3),
    };
}
于 2012-01-09T14:02:04.467 に答える
1

ボタンの 1 つが null である可能性があります。また、private キーワードを入力しても、配列を作成できません。また、最初にアクティビティの cententView を設定してから、これらのボタンにアクセスしていることも確認してください。

于 2012-01-09T13:01:37.403 に答える
1

試してみませんか

final Button[] button = {(Button) findViewById(R.id.cGuess1), 
    (Button) findViewById(R.id.cGuess2),(Button) 
    findViewById(R.id.cGuess3),(Button) findViewById(R.id.cGuess4)};
于 2012-01-09T12:57:18.813 に答える
1

ここでは完全なコードが利用できないため、配列を作成する前に setContentView() を呼び出したかどうかを推測してください。

于 2012-01-09T13:04:56.683 に答える