1

私は一生これを理解することはできず、できる限り徹底的に検索しました.

私は次のようなコードのブロックを持っています:

    public class TwoPlayerGame extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);                    
}



public GameStuff game = new GameStuff();
public Player playerOne = new Player();
public Player playerTwo = new Player();

public Player[] players = {playerOne, playerTwo};

public Button cardOne=(Button)findViewById(R.id.card1);
public Button cardTwo=(Button)findViewById(R.id.card2);
public Button cardThree=(Button)findViewById(R.id.card3);
public Button cardFour=(Button)findViewById(R.id.card4);
public Button cardFive=(Button)findViewById(R.id.card5);

public Button[] buttons={cardOne, cardTwo, cardThree, cardFour, cardFive};

@Override
public void onStart(){
    super.onStart();


    for(int i=0; i<=1; i++){
        dealCards(players[i]);
    }



    for (int i = 0; i<=4; i++){
        buttons[i].setText(playerOne.cardsInHand[i]);
    }


}


}

書かれているように、これはアクティビティが開始されるとすぐにクラッシュします (onStart オーバーライドを新しいメソッドに完全に変更すると、クラッシュすることさえあります)。すべての Button 宣言を onStart メソッドに移動すると、すべて正常に動作しますが、グローバルにはなりません。それらを onCreate に移動すると、Eclipse によるとそれらはグローバルにならず、コンパイルできないエラーが発生します。

他のすべてのグローバル変数はどこでも問題なく機能します。ボタンをグローバルにする必要があるため、新しいメソッドでそれらを再宣言し続ける必要はありません。

私は目がくらむほど明白な何かを見落としていますか (おそらく)? で、それ何?

4

2 に答える 2

0

試す

    public class TwoPlayerGame extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        cardOne=(Button)findViewById(R.id.card1);
        cardTwo=(Button)findViewById(R.id.card2);
        cardThree=(Button)findViewById(R.id.card3);
        cardFour=(Button)findViewById(R.id.card4);
        cardFive=(Button)findViewById(R.id.card5);

    }


public GameStuff game = new GameStuff();
public Player playerOne = new Player();
public Player playerTwo = new Player();

public Player[] players = {playerOne, playerTwo};

public Button cardOne;
public Button cardTwo;
public Button cardThree;
public Button cardFour;
public Button cardFive;

public Button[] buttons={cardOne, cardTwo, cardThree, cardFour, cardFive};

@Override
public void onStart(){
    super.onStart();


    for(int i=0; i<=1; i++){
        dealCards(players[i]);
    }



    for (int i = 0; i<=4; i++){
        buttons[i].setText(playerOne.cardsInHand[i]);
    }


}


}

を呼び出す前に を取得Buttonsすることはできません。それは無理だ。findViewByIdsetContentView

于 2012-10-15T20:19:44.397 に答える
0

あなたはその行を認識する必要があります

public Button cardOne=(Button)findViewById(R.id.card1);
... and others

クラスの作成時に呼び出されます。ただし、これは onCreate が呼び出される前です。findViewById を使用するには最初に呼び出す必要があるため、クラッシュします

setContentView(R.layout.activity_game);

ただし、実際にはクラスの初期化後、したがって findViewById の呼び出し後に呼び出されます。

于 2012-10-15T20:21:34.770 に答える