gpt4 book ai didi

Android 将基本计时器转换为 RxJava

转载 作者:行者123 更新时间:2023-11-29 19:21:29 25 4
gpt4 key购买 nike

我创建了一个简单的计时器,它从 0 到 30 计数,间隔为 1 秒。我想达到同样的效果,但它必须从 30 计数到 0,并且必须使用 RxJava 来完成。有人可以给我提供样本转换吗?

这是我的代码:

 TextView timerTextView;
long startTime = 0;

//runs without a timer by reposting this handler at the end of the runnable
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {

@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;

timerTextView.setText(String.format("%d:%02d", minutes, seconds));

timerHandler.postDelayed(this, 500);
}
};

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

timerTextView = (TextView) findViewById(R.id.textView);

Button b = (Button) findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerTextView.setText("0:00");
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});

timerTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(timerTextView.getText().toString().equals("0:30")){
Toast.makeText(MainActivity.this, "End of time!", Toast.LENGTH_SHORT).show();
}
}

@Override
public void afterTextChanged(Editable s) {
}
});
}

最佳答案

它不必很复杂:

Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.take(31) // 0, 1, 2, ..., 30
.map(new Func1<Long, Integer>() {
@Override public Integer call(Long value) {
return 30 - value.intValue();
}
})
.subscribe(new Action1<Integer>() {
@Override public void call(Integer value) {
System.out.println(value);
}
});

关于Android 将基本计时器转换为 RxJava,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42329919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com