开发者

implement timer in my app

i am developing a game.i want to display score on button click.but it should be displayed only for few seconds.i want to implement timer in my app.but i dnt knw how to implement that.i searched in the google.but results were confusing me...given below is my code snippet.plz anybody help me...

        OnClickListener clickball=new OnClickListener() {

        @Override
        public void onClick(View v) {

            score=scorenumber.nextInt(9);
            id=v.getId();

             Log.v("", "u clicked me");
            if(id==R.id.ball2)
            {
      开发者_如何学Go          ball2.setText(Integer.toString(score));
            }
            else if(id==R.id.ball3)
            {
                ball3.setText(Integer.toString(score));
            }
            else if(id==R.id.ball5)
            {
                ball5.setText(Integer.toString(score));
            }

} }


Something like

//Show score here

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    public void run() {
            //hide score here
        }
}, 2000);

will hide your score after two seconds.


No need to go so deep in your case. Every view has postDelayed() method, that will run a custom code in UI thread after a set amount of time (in milliseconds). For example:

ball5.postDelayed(new Runnable(){
            @Override
            public void run() {
                ball5.setText("");
            }
        }, 3000);

will clear "ball5" text after 3 seconds has passed

Another example ...

if(id==R.id.ball2)
            {
                ball2.setText(Integer.toString(score));
ball2.postDelayed(new Runnable(){
            @Override
            public void run() {
                ball2.setText("");
            }
        }, 3000);
            }

...


you can use CountDownTimer(); refer the documentation ,

Example :

new CountDownTimer(5000,1000) {

        @Override
        public void onTick(long millisUntilFinished) {}

        @Override
        public void onFinish() {
            //hide your score here after 5 secondes (5000/1000)
        }
    }.start();


I think CountDownTimer is that what you need:http://developer.android.com/reference/android/os/CountDownTimer.html . It's quite simle for implementation

 new CountdownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
 }

 public void onFinish() {
     mTextField.setText("done!");
 } 

}.start();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜