0

我试图取消 onbackpressed 上的倒数计时器,我把 counter.cancel; 那里但出现“'count'无法解决”错误。我想它找不到倒数计时器!有一个 btn_riazi1_1_1 可以取消定时器。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_riazi1_1);


    //// handling timer
    final TextView textic = (TextView) findViewById(R.id.riazi1_1_timer);

    final CountDownTimer Count = new CountDownTimer(5000, 1000) {
        public void onTick(long millisUntilFinished) {

            textic.setText(getResources().getString(R.string.remaintime) + millisUntilFinished / 1000);
        }



        public void onFinish() {
            textic.setText(getResources().getString(R.string.timesup));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {



                    Intent i=new Intent(Riazi1_1.this,Riazi1_2.class);

                    startActivity(i);
                }
            }, 1000);

        }
    };

    Count.start();
    /////////////////


    //// handling button1
    Button btn1 = (Button) findViewById(R.id.btn_riazi1_1_1);
    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Count.cancel();

            TextView txtwrong = (TextView) findViewById(R.id.txt_wrong_riazi1_1);
            txtwrong.setVisibility(View.VISIBLE);

            Button btn2 = (Button) findViewById(R.id.btn_riazi1_1_2);
            btn2.setBackgroundColor(Color.GREEN);


            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {



                    Intent i=new Intent(Riazi1_1.this,Riazi1_2.class);

                    startActivity(i);
                }
            }, 1000);



        }
    });

 }

 @Override
public void onBackPressed(){

    super.onBackPressed();
    Count.cancel();     //   error:  Count cannot be resolved ///

}
 }
4

1 回答 1

1

您已经在 onCreate 方法中声明了 TIMEr。所以你不能在 onCreate 之外访问它。将其声明为成员变量。

private CountDownTimer Count; /// declare it as a member variable

并在 onCreate 方法中像这样初始化它

Count = new CountDownTimer(5000, 1000).....

[一个建议,使用命名约定。命名以大写字母开头的变量真的很混乱]

于 2013-06-29T08:04:09.357 回答