为什么声明全局变量会导致应用程序强制关闭

时间:2015-07-16 14:01:54

标签: android global-variables main-activity

当变量在onCreate范围内时,它工作正常,但我也需要在onDestroy范围内使用变量,所以我把它作为全局变量。但是我的应用程序在打开时关闭了。

public class MainActivity extends Activity {

    GamePanel gamePanel = new GamePanel (this);
    EditText editText = (EditText) getLayoutInflater().inflate(R.layout.edit_text_template, null);

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    //Remove title
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    //Set fullscreen
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


    RelativeLayout.LayoutParams gameParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    gamePanel.setLayoutParams(gameParams);

    RelativeLayout.LayoutParams etParams = new RelativeLayout.LayoutParams(
            300, 100);
    etParams.leftMargin = 200;
    etParams.topMargin = 800;
    editText.setLayoutParams(etParams);

    RelativeLayout content = new RelativeLayout(this);

    content.addView(gamePanel);
    content.addView(editText);

    setContentView(content);
}

@Override
protected void onDestroy(){
    super.onDestroy();
}


}

如代码所示,我想使用gamePanel和editText作为全局变量。知道怎么做吗?或者我错过了什么?提前谢谢。

1 个答案:

答案 0 :(得分:3)

您应该在OnCreate()

中初始化您的变量
 GamePanel gamePanel;
    EditText editText;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    gamePanel = new GamePanel (this);
    editText = (EditText) getLayoutInflater().inflate(R.layout.edit_text_template, null);

...}