gpt4 book ai didi

java - 在 onCreate 外部声明变量 - Android

转载 作者:行者123 更新时间:2023-12-01 18:27:17 26 4
gpt4 key购买 nike

当我在 onCreate 方法之外声明 TextView 时,我的应用程序将停止,我这样做是因为我还需要从其他方法访问 TextView 变量。我将不胜感激任何形式的帮助。

public class MainActivity extends ActionBarActivity {
TextView textView = (TextView)findViewById(R.id.defaultText);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);

textView.setText("Hello");
}
}

最佳答案

My application stops when I declare the TextView outside the onCreate method

这是因为布局尚未在您的 Activity 中膨胀,从而使您的应用程序崩溃,并且我100%确定当您在此处设置文本时,错误是NPE: textView.setText("Hello");.

解决方案:

始终在 setContentView 之后在 Oncreate 中初始化 TextView,并将 textView 对象作为全局实例。

public class MainActivity extends ActionBarActivity {
TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);

textView = (TextView)findViewById(R.id.defaultText);
textView.setText("Hello");
}
}

关于java - 在 onCreate 外部声明变量 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25633069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com