计时器在初始按钮点击时启动

时间:2015-10-08 18:29:20

标签: android chronometer

我的所有代码都可以正常工作没有错误,每次点击按钮点击都会使textview增加1并启动计时器。

public class MainActivity extends Activity{

    TextView txtCount;
    Button btnCount;
    int count=0;
    Chronometer chrono;

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

        chrono=(Chronometer) findViewById(R.id.chronometer);
        txtCount=(TextView) findViewById(R.id.textView);
        btnCount=(Button)findViewById(R.id.button);

        btnCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            //onclick increase textView by 1
                count++;
                txtCount.setText(String.valueOf(count));
            //on button click start the chronometer at 00:00
                btnCount.setEnabled(true);
                chrono.setBase(SystemClock.elapsedRealtime());
                chrono.start();

            }
    });
}}

...但是,正如我的代码所示,计时器被重置并开始每按一次按钮。有没有办法在第一次按钮点击时启动计时器,然后继续使用相同的按钮增加textview但没有与计时器小部件的交互?

1 个答案:

答案 0 :(得分:0)

只需使用布尔值来检查你的计时表是否已经启动?

boolean mIsStarted = false;
...

btnCount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        //onclick increase textView by 1
            count++;
            txtCount.setText(String.valueOf(count));
        //on button click start the chronometer at 00:00
            btnCount.setEnabled(true);
            if (!mIsStarted) {
                chrono.setBase(SystemClock.elapsedRealtime());
                chrono.start();
                mIsStarted = true;
            }

}