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

chronometer start on initial button click

我的所有代码都工作正常,没有错误,每次单击按钮都会将 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 但没有与计时器小部件的交互?

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

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;
            }

}