问题
I'm creating a quiz app where randomly generating tasks, but I don't know how to wait for user click in for loop. I tried to do this:
final Integer min=1;
final Integer max=100;
for (int i = 0; i<5; i++){
button_check3.setVisibility(View.VISIBLE);
button_next3.setVisibility(View.INVISIBLE);
final int x = new Random().nextInt(max - min)+min;
final int y = new Random().nextInt(max-x - min)+min;
task3.setText(x + " + " + y + " ="); //set task
final int zbroj = x+y;
button_check3.setOnClickListener(new View.OnClickListener() { //check user answer
@Override
public void onClick(View v) {
button_check3.setVisibility(View.INVISIBLE);
button_next3.setVisibility(View.VISIBLE);
String user_answer=answer3.getText().toString();
if (user_answer.equals(zbroj)){
check3.setImageResource(R.drawable.true_);
}
else {
check3.setImageResource(R.drawable.wrong_);
}
}
});
button_next3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//continue for loop
}
});
}
I want to:
- generate task
- wait for user click check button and check answer
- wait for user click next button
- continue loop
I want to repeate this five times. I saw this question before but I didn't find what I need. Thank you.
回答1:
You can make next:
class LoopActivity : AppCompatActivity() {
val button1: Button = findViewById()
val button2: Button = findViewById()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(/*layout*/)
imitationLoop(false)
}
fun imitationLoop(needBreak: Boolean) {
if (!needBreak) {
someCode1()
button1.setOnClickListener {
button1.setOnClickListener { }
someCode2()
button2.setOnClickListener {
button2.setOnClickListener { }
imitationLoop(/*conditionBreak*/)
}
}
}
}
fun someCode1() {
//somecode
}
fun someCode2() {
//somecode
}
}
It's recursion. And you need condition for break recursion. If you want condition for as look (int i=0; i<10; i++):
class LoopActivity : AppCompatActivity() {
val button1: Button = findViewById()
val button2: Button = findViewById()
var i: Int = 0
var max: Int = 10
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(/*layout*/)
imitationLoop(false)
}
fun imitationLoop(needBreak: Boolean) {
if (!needBreak) {
someCode1()
button1.setOnClickListener {
button1.setOnClickListener { }
someCode2()
button2.setOnClickListener {
button2.setOnClickListener { }
imitationLoop(i++ < max)
}
}
}
else {
i = 0
}
}
fun someCode1() {
//somecode
}
fun someCode2() {
//somecode
}
}
来源:https://stackoverflow.com/questions/63009612/how-to-pause-for-loop-and-wait-for-user-click