使用android.widget.Button类作为全局变量时应用程序崩溃

时间:2012-10-15 20:16:10

标签: android

我不能为我的生活弄清楚这一点,我尽可能彻底地搜索。

我有一块像这样的代码:

    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方法中,一切正常,但它们将不是全局的。如果我将它们移动到onCreate,它们将不会是全局的,根据Eclipse,我得到的错误不会让我编译。

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

我是否忽略了一些非常明显的事情(可能)?它是什么?

2 个答案:

答案 0 :(得分: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之前,您无法从findViewById获取setContentView。是不可能的。

答案 1 :(得分:0)

你应该意识到这些行

public Button cardOne=(Button)findViewById(R.id.card1);
... and others
创建类时会调用

。但这是在onCreate被召唤之前。它崩溃是因为要使用findViewById,你需要先调用

setContentView(R.layout.activity_game);

但它实际上在类初始化之后调用,因此在findViewById调用之后调用。