我的程序应该重复一个方法,直到按下按钮。 我想这一点,但不工作:Android编程:我如何摆脱while循环?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
public void onClick (View v){
switch(v.getId()) {
case R.id.button1:
mainprogram();
break;
case R.id.button2:
perform = false;
break;
}
}
public void mainprogram(){
while(perform == true){
speak();
}
}
(当然我编写的“说话()”方法)
你能告诉我哪里出了问题或者有任何方法解决它?
:
你可以阅读更多有关挥发性这里。你可能想把方法代码放到循环中,然后使用break;'在循环外部 – SMR
使'perform'成为'transient'。由于优化编译器,while循环总是为true。当你进入transient循环时,'perform'值会在进入while循环之前被检查。 – Rahul