我正在尝试创建一个Android应用程序,该应用程序应该在几分钟内从搜索栏获得时间,然后它应该开始播放声音文件,直到倒数计时器结束。
倒数计时器几乎没什么问题,但我的问题是,当按下按钮时,如何调用倒数计时器实例的某些方法。
在下面的代码中,我想在按下停止按钮时调用onFinish()。
这是我的代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBar sb = (SeekBar) findViewById(R.id.seekBar);
Button bt_stop = (Button) findViewById(R.id.btn1);
final TextView tv = (TextView)findViewById(R.id.textView);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
int millisec_time = (i*60)/1000;
new CountDownTimer(millisec_time, 1000) {
public void onTick(long millisUntilFinished) {
tv.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
tv.setText("done!");
}
}.start();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Toast.makeText(getApplicationContext(),"GOT",Toast.LENGTH_LONG).show();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Toast.makeText(getApplicationContext(),"OFF",Toast.LENGTH_LONG).show();
}
});
bt_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
}
答案 0 :(得分:1)
首先,我建议您仅在CountdownTimer
中启动onStopTrackingTouch
-原因是当前每次搜索栏上的进度更改时,您都在创建一个全新的计时器(这可能会发生很多)。
第二,您需要保留对计时器的引用才能将其取消。所以:
public class MainActivity extends AppCompatActivity {
private CountdownTimer timer = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SeekBar sb = (SeekBar) findViewById(R.id.seekBar);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
restartTimer(seekBar);
}
}
final Button bt_stop = (Button) findViewById(R.id.btn1);
bt_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(timer != null) {
timer.cancel();
}
}
});
}
private void restartTimer(SeekBar sb) {
if(timer!=null) {
timer.cancel();
}
final long millis = TimeUnit.SECONDS.toMillis(sb.getProgress());
final long interval = TimeUnit.SECONDS.toMillis(1);
timer = new CountdownTimer(millis, interval) {
@Override
public void onTick(long millisUntilFinished) {
tv.setText(String.format("Seconds Remaining: %d", TimeUnit.MILLIS.toSeconds(millisUntilFinished));
}
@Override
public void onFinish() {
tv.setText("done!");
}
}
timer.start();
}
}