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

Why does declaring global variables result in application force close

当变量在 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 作为全局变量。知道怎么做吗?或者我错过了什么?提前致谢。

您应该在 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);

...}