onClick方法[重复项]中无法识别可变TextView

问题描述 投票:-1回答:3

你好,我有以下代码.....当我点击按钮时,打印你好+ edittex中的名称enter image description here

我分两个步骤声明了textview,没有问题。但是,如果我更改代码....enter image description here

tv1在askQuestion方法中无法识别。...为什么?之间的区别是什么:

TextView tv1;
.
.
tv1 = findViewById(R.id.textView1);

TextView tv1 = findViewById(R.id.textView1);
android findviewbyid
3个回答
1
投票
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
}

1
投票

当在tv1方法中将onCreate变量声明为局部变量时,声明后只能在onCreate方法中使用它。如果要在tv1类的其他方法中使用MainActivity变量,则应像在第一张图片中一样在类中声明它。


1
投票

使用此

TextView tv1 = findViewById(R.id.textView1);
© www.soinside.com 2019 - 2024. All rights reserved.