非静态方法start()不能从静态上下文中引用

时间:2016-02-27 21:28:26

标签: java android timer countdowntimer

当我尝试在按钮中添加“开始”和“取消”时,我收到此错误。 我查看了Timer文件但我没有看到任何内容 "错误:非静态方法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();

            }
        }
    });


    }


}

3 个答案:

答案 0 :(得分:0)

您需要创建一个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();
            }
        }
    });
}

答案 1 :(得分:0)

您正在尝试使用非静态方法,例如静态方法。尝试创建一个变量来存储CountDownTimer的实例并在其上调用方法。还有doc:http://developer.android.com/reference/android/os/CountDownTimer.html

答案 2 :(得分:0)

您需要创建一个CountDownTimer实例,如下所示:

CountDownTimer timer = new CountDownTimer(100000, 1000){...}

然后,在onClick方法中:

if (y) {
   timer.start();
   y= true;
}
else {
   y = false;
   timer.cancel();

}