如何声明TextView变量,以便可以在任何地方使用它? [英] How do I declare a TextView variable so that I can use it anywhere?
问题描述
我今天才开始用java/android进行编码,请原谅我在这里是个白痴.
I have started coding in java/android just today so excuse me if I am being a total idiot here.
过去一个小时我一直在面对这个问题,我曾尝试用Google搜索它,但找不到任何答案.
I have been facing this problem for the past hour, I have tried to google it but couldn't find any answers.
如何将TextView声明为静态/变量,以便只需键入变量名"即可访问它.我代码中的任何地方?
How do I declare a TextView as a static/variable so that I can access it simply by typing "variablename." anywhere in my code?
我不是试图从另一个活动访问TextView,这些都在同一个活动中.
I am not trying to access the TextView from another activity, these are all in the same one.
这是我的代码的样子(全部在mainactivity.java中):
This is what my code looks like(all in mainactivity.java) :
public class MainActivity extends Activity {
TextView test = (TextView)findViewById(R.id.textView2);
public void registermessage(View view) {
test.setText("Test");
}
}
这不会在Eclipse中产生任何错误,而只是在我尝试在手机上运行时将其强制关闭.
This doesn't give any errors in Eclipse but will simply force close when I try to run it on my phone.
当我将声明为textview的行移动到公共void上时,我可以成功,但是我希望能够从活动中的任何void中使用变量test.
I can succeed when I move the line I declare test as a textview to the public void but I want to be able to use the variable test from any void in the activity.
谢谢!
推荐答案
在调用 setcontentView
方法之后,您必须实例化变量,因此您必须执行以下操作:
You have to instantiate the variable after the setcontentView
method was called, so you have to do the following:
public class MainActivity extends Activity {
TextView test;
@Override
onCreate(Bundle s){
...
setContentView(R.layout.yourLayout);
test = (TextView)findViewById(R.id.textView2);
}
public void registermessage(View view) {
test.setText("Test");
}
这篇关于如何声明TextView变量,以便可以在任何地方使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!