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


}


}

正如所写的那样,一旦 Activity 启动,它就会崩溃(如果我将 onStart 覆盖完全更改为新方法,它甚至会崩溃)。如果我将所有 Button 声明移到 onStart 方法中,一切正常,但它们不会是全局的。根据 Eclipse,如果我将它们移到 onCreate 中,它们将不是全局的,并且我会遇到无法编译的错误。

所有其他全局变量在它们所在的位置都可以正常工作,并且我需要按钮是全局的,因此我不必继续在新方法中重新声明它们。

我是否忽略了一些非常明显的东西(可能)?还有,这是什么?

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


}


}

你不能ButtonsfindViewById之前的电话中得到setContentView。是不可能的。

于 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 回答