我在onCreate中有以下代码:
final TextView text1 = (TextView) findViewById(R.id.txtNextAlarm);
我尝试在同一类中的一个方法中设置文本:
public static void NextTxt(){
text1.setText("");
}
但它无法识别 "text1"。
我在onCreate中有以下代码:
final TextView text1 = (TextView) findViewById(R.id.txtNextAlarm);
我尝试在同一类中的一个方法中设置文本:
public static void NextTxt(){
text1.setText("");
}
text1
变量甚至都不是这样。相反,它是一个仅存在于onCreate()
方法长度内的局部变量。如果你知道你的活动只会有一个实例(这可能是合理的假设),你可以使用...private static TextView text1;
final
修饰符没有什么帮助。你可以选择将其设置为公有或私有,但我倾向于默认设置为私有(除非有其他原因)。NextTxt()
是静态的;如果你将它作为普通实例方法,则仍需要在类中声明text1
,但它不需要是静态的。但是你仍需要一个实例来调用它。TextView text1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
text1 = (TextView) findViewById(R.id.txtNextAlarm);
}
在onCreate方法中进行初始化。
如果方法是静态的,您无法访问类的任何非静态字段。您必须将textField设置为静态或将其作为参数传递。
static TextView text1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyClass.text1 = (TextView) findViewById(R.id.txtNextAlarm);
}
public static void NextTxt(){
MyClass.text1.setText("");
}
final TextView text1 = (TextView) findViewById(R.id.txtNextAlarm);
text1是一个本地
变量,您必须将其声明为类的属性
public final TextView text1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
text1 = (TextView) findViewById(R.id.txtNextAlarm);
}
在你的静态方法中使用:
public static void NextTxt(){
text1.setText("");
}