Android 循环点击按钮直到参数不正确
Android loop on button click until argument not true
所以我在 Android Studio 中闲逛,尝试设置按钮循环直到 counter<=3。但是,如果我单击模拟器中的按钮,它只会跳到 "if" 之后的语句,这是为什么呢?该按钮是否快速连续执行我在 while 中指定的操作,而不是每次单击 1 次?我如何解决它?
无论如何,这里是摘录代码:
button.setOnClickListener(new Button.OnClickListener() {
TextView myTextView;
int counter = 0;
public void onClick(View v) {
while(counter<=3){
myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("Button clicked");
counter++;
}
if(counter==4){
myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("hello");}
}
while 循环将反复执行,即使它只被调用一次(每次点击)。这就是为什么它被称为循环。您需要将其更改为 if 语句 - 每次点击将执行一次。
此外,我建议您在 activity 的顶部而不是在点击侦听器中全局声明您的 TextView 和计数器。然后在 onCreate()
中分配你的 TextView
和你想的一样,while循环只是一直执行到counter不再<= 3,然后if(counter==4)为真,if语句执行...
button.setOnClickListener(new Button.OnClickListener() {
TextView myTextView;
int counter = 0;
public void onClick(View v) {
if (counter == 4) {
myTextView = (TextView) findViewById(R.id.myTextView);
myTextView.setText("hello");
} else {
myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("Button clicked");
counter++;
}
}
});
所以我在 Android Studio 中闲逛,尝试设置按钮循环直到 counter<=3。但是,如果我单击模拟器中的按钮,它只会跳到 "if" 之后的语句,这是为什么呢?该按钮是否快速连续执行我在 while 中指定的操作,而不是每次单击 1 次?我如何解决它? 无论如何,这里是摘录代码:
button.setOnClickListener(new Button.OnClickListener() {
TextView myTextView;
int counter = 0;
public void onClick(View v) {
while(counter<=3){
myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("Button clicked");
counter++;
}
if(counter==4){
myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("hello");}
}
while 循环将反复执行,即使它只被调用一次(每次点击)。这就是为什么它被称为循环。您需要将其更改为 if 语句 - 每次点击将执行一次。
此外,我建议您在 activity 的顶部而不是在点击侦听器中全局声明您的 TextView 和计数器。然后在 onCreate()
中分配你的 TextView和你想的一样,while循环只是一直执行到counter不再<= 3,然后if(counter==4)为真,if语句执行...
button.setOnClickListener(new Button.OnClickListener() {
TextView myTextView;
int counter = 0;
public void onClick(View v) {
if (counter == 4) {
myTextView = (TextView) findViewById(R.id.myTextView);
myTextView.setText("hello");
} else {
myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("Button clicked");
counter++;
}
}
});