繁体   English   中英

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

[英]non-static method start() cannot be referenced from a static context

当我尝试在按钮中添加“开始”和“取消”时,出现此错误。 我查看了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();

            }
        }
    });


    }


}

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM