单击按钮时如何设置定时器?

时间:2015-08-31 05:47:21

标签: java android timer

我的意思是像止步,当点击按钮时,定时器开启,直到按下停止按钮

startbutton= (Button)findViewById(R.id.black1);
  startbutton.setOnClickListener(new View.OnClickListener() {

              public void onClick(View v){
              //Start the timer
                                         }                
            });

 stopbutton= (Button)findViewById(R.id.black1);
 stopbutton.setOnClickListener(new View.OnClickListener() {

              public void onClick(View v){
              //Stop the timer
                                         }                
            });

和第二个问题,

如果计时器显示90秒如何让它在屏幕上显示imageview或按钮?就像一些if语句使按钮可见,每个计时器计数到90秒(90,180,270等等),他将按钮可见性设置为可见。

先谢谢。

2 个答案:

答案 0 :(得分:4)

xml

中使用天文台表
<Chronometer
        android:id="@+id/chronometer1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Chronometer" />

java

Chronometer focus = (Chronometer) findViewById(R.id.chronometer1);

startButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        focus.start();
        setVisibilityTimerOn(); //Second Question Solution
    }
});

stopButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        focus.stop();
        setVisibilityTimerOff();
    }
});

第二个问题如果要打开/关闭某个按钮的可见性/ ImageView设置处理程序

//Declare these variable 
private Handler handler;
private Runnable updateView;


private void setVisibilityTimerOn(){
     timeHandler = new Handler(); //it's better if you declare this line in onCreate (becuase if user press stopButton first before pressing startButton error will occur as handler was never initialized and you try calling removeCallback function)
     updateView = new Runnable() {
         public void run() {
              someImageView.setVisibility(View.VISIBLE);
         }
     };
     handler.postDelayed(updateView ,90000);//this will be on after 90 second
}

private void setVisibilityTimerOff(){
    handler.removeCallbacks(updateView);
}

答案 1 :(得分:0)

这就像秒表计时器一样,间隔为1毫秒。

    Handler handler= new Handler();

1. click to start   (code)


  Runnable runnable = new Runnable() {
                       @Override
                       public void run() {
        //put your code to be executed on within every interval
                           handler.postDelayed(this, 1); 
                       }
                    };

        handler.postDelayed(runnable, 5); //start after 5 seconds 

 2. click to stop (code)
     handler.removeCallbacksAndMessages(null); 

它应该工作。         感谢