非静态方法start()不能从静态上下文中引用
问题描述:
当我试图在按钮中添加Start和Cancel时,出现此错误。 我看着计时器的文件,但我没有看到任何 “错误:非静态方法start()方法不能从静态上下文中引用”非静态方法start()不能从静态上下文中引用
public int number;
public TextView textfield;
Button buton;
int x = 1;
Boolean y = false;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading);
new CountDownTimer(100000, 1000) {
public void onTick(long millisUntilFinished) {
textfield.setText("Time: " + millisUntilFinished/1000);
}
public void onFinish() {
textfield.setText("Time is up");
}
}.start();
textfield=(TextView)findViewById(R.id.Zamanlayici);
buton=(Button)findViewById(R.id.Click);
buton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//My Error is in there :(
if (y) {
CountDownTimer.start();
y= true;
}
else {
y = false;
CountDownTimer.cancel();
}
}
});
}
}
答
您需要创建的CountDownTimer
一个实例调用来自它的非静态方法。
CountDownTimer timer = new CountDownTimer();
timer.start();
你的代码改成这样
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading);
CountDownTimer timer = new CountDownTimer(100000, 1000) {
public void onTick(long millisUntilFinished) {
textfield.setText("Time: " + millisUntilFinished/1000);
}
public void onFinish() {
textfield.setText("Time is up");
}
}
timer.start();
textfield=(TextView)findViewById(R.id.Zamanlayici);
buton=(Button)findViewById(R.id.Click);
buton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (y) {
timer.start();
y= true;
}
else {
y = false;
timer.cancel();
}
}
});
}
答
您要使用像一个静态不是一成不变的方法。尝试创建一个变量来存储CountDownTimer的实例并调用它的方法。此外DOC:http://developer.android.com/reference/android/os/CountDownTimer.html
答
您需要创建CountDownTimer的实例,像这样:然后
CountDownTimer timer = new CountDownTimer(100000, 1000){...}
,在onclick方法:
if (y) {
timer.start();
y= true;
}
else {
y = false;
timer.cancel();
}
+0
错误:(55,21)错误:局部变量t从内部类中访问;需要被宣布为最终 – Thorin
当地varriable定时器从内部类访问;需要最终删除 – Thorin
非常感谢你 – Thorin