[英]findViewById method outside the onCreate method?
lately, I was working on a very small training project.最近,我在做一个非常小的培训项目。 But there is one error in my code:但是我的代码中有一个错误:
public class MainActivity extends AppCompatActivity {
TextView textView = (TextView) findViewById(R.id.textview);
@override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView.setText("Welcome");
}
}
but when I tried to cut the textview global variable and paste it inside the onCreate method, the error has gone.但是当我尝试剪切 textview 全局变量并将其粘贴到 onCreate 方法中时,错误消失了。 Why is this error occur although I already have inflated the textView in a global variable?!尽管我已经在全局变量中膨胀了 textView,但为什么会出现此错误?!
You need to call findViewById(...)
after calling setContentView(...)
.您需要在调用setContentView(...)
findViewById(...)
...) 。
Fetching the view before inflating the layout isn't possible since there is no view.由于没有视图,因此无法在扩展布局之前获取视图。
findViewById()
should only be used after setContentView()
in onCreate. findViewById()
只能在 onCreate 中的setContentView()
之后使用。
That's where your entire layout get inflated.这就是你的整个布局被夸大的地方。 Only then you can access views using findViewById()
.只有这样您才能使用findViewById()
访问视图。
This is what you want:这就是你想要的:
public class MainActivity extends AppCompatActivity {
TextView textView;
@override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
textView.setText("Welcome");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.