你好,我有以下代码.....当我点击按钮时,打印你好+ edittex中的名称
我分两个步骤声明了textview,没有问题。但是,如果我更改代码....
tv1在askQuestion方法中无法识别。...为什么?之间的区别是什么:
TextView tv1;
.
.
tv1 = findViewById(R.id.textView1);
和
TextView tv1 = findViewById(R.id.textView1);
TextView tv1;
.
.
tv1 = findViewById(R.id.textView1);
情况1:tv1是全局变量。
TextView tv1 = findViewById(R.id.textView1);
情况2:tv1是局部变量。它仅用于onCreate
我想如果您不想像情况1那样定义全局变量,则可以将tv1传递给askQuestion()
样本
void onCreate(){
askQuestion(tv1);
}
void askQuestion(Textview tv1){
//TODO use tv1
}
当在tv1
方法中将onCreate
变量声明为局部变量时,声明后只能在onCreate
方法中使用它。如果要在tv1
类的其他方法中使用MainActivity
变量,则应像在第一张图片中一样在类中声明它。
使用此
TextView tv1 = findViewById(R.id.textView1);