1 回答
TA贡献1830条经验 获得超9个赞
如果您在 if 条件中放置一个日志,您会在 00:05 之后在 logcat 中看到该日志。我通过从计时器上移除监听器来防止它。
chrono.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer chronometer) {
if(chronometer.getText().toString().equalsIgnoreCase("00:05")) {
// Reset Chronometer
chronometer.setOnChronometerTickListener(null);
chronometer.stop();
chronometer.setBase(SystemClock.elapsedRealtime());
}
}
});
但是如果你需要这个监听器,你可以从Chronometer.OnChronometerTickListener实现你的片段并实现 OnChronometerTickListener ,如下所示:
public class MainActivity extends AppCompatActivity implements Chronometer.OnChronometerTickListener {
private String TAG = "MainActivity";
Button start;
Chronometer chronometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chronometer = findViewById(R.id.chron);
start = findViewById(R.id.btn);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chronometer.start();
}
});
chronometer.start();
chronometer.setOnChronometerTickListener(this);
}
@Override
public void onChronometerTick(Chronometer chronometer) {
if (chronometer.getText().toString().equalsIgnoreCase("00:05")) {
// Reset Chronometer
chronometer.setOnChronometerTickListener(null);
chronometer.stop();
Log.d(TAG, "onChronometerTick: stop");
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.setOnChronometerTickListener(this);
}
}
}
添加回答
举报