[英]How can I start and stop a for loop with the press of a button in Android Studio?
我做了一個點擊按鈕,它通過一個列表並取出單個項目並通過藍牙將它們發送到硬件。
我想要做的是,當我再次單擊該按鈕時,它應該停止中間循環的執行,並且不再發送任何值。
我試過用一個變量來制作它,它在點擊時變成真和假,只有當變量為真時循環才會繼續。
這里是:
run.setOnClickListener{
if (!stop){
stop = true
runList()
}
else{
stop = false
}
}
private fun runList() {
for (i in 0 until order.size) {
if(stop) {
//Elements to send come here, using order[i]
}
if (!stop) {
break
}
}
}
但是在這段代碼中,即使我在執行之間再次單擊按鈕,循環也會一直持續到所有項目完成時的最后。 有人可以幫幫我嗎?
我認為你的邏輯很混亂。 試試這個。
run.setOnClickListener{
if (!stop){
stop = true
}else{
stop = false
}
runList();
}
private fun runList() {
if(stop){
for (i in 0 until order.size) {
//Elements to send come here, using order[i]
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.