Java 代码只能有条件地工作?
当我按下按钮一次时,while循环停止并显示消息,但当我再次按下按钮时,while循环不会再次启动,我知道这一点,因为runnable中的消息不会显示 还有,组合的同时!线程中有boo,boo=true;在按钮中不会产生任何结果 我可能做错了什么?我把布尔boo=true;在外面,所以我不认为这是问题所在Java 代码只能有条件地工作?,java,android,if-statement,while-loop,Java,Android,If Statement,While Loop,当我按下按钮一次时,while循环停止并显示消息,但当我再次按下按钮时,while循环不会再次启动,我知道这一点,因为runnable中的消息不会显示 还有,组合的同时!线程中有boo,boo=true;在按钮中不会产生任何结果 我可能做错了什么?我把布尔boo=true;在外面,所以我不认为这是问题所在 public class UiTester extends Activity { protected static final String TAG = null; St
public class UiTester extends Activity {
protected static final String TAG = null;
String s="";
Button stopper;
TextView display3;
//Boolean boo=true;
int n=0;
public Boolean boo=true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
on=(Button) findViewById(R.id.bon);
off=(Button) findViewById(R.id.boff);
display=(TextView) findViewById(R.id.tvdisplay);
display3=(TextView) findViewById(R.id.tvdisplay3);
stopper=(Button) findViewById(R.id.stops);
final Handler handler = new Handler();
final Runnable updater = new Runnable() {
public void run() {
n++;
display3.setText("System On"+n);
}
};
stopper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(boo==true)
{
boo=false;
display3.setText("System Off");
}
else{
boo=true;
}
}
});
Thread x = new Thread() {
public void run() {
while (boo) {
handler.post(updater);
//non UI elements can go here
try {
Log.d(TAG, "local Thread sleeping");
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e(TAG, "local Thread error", e);
}
}
}
};
x.start();
}
}
当boo为false时,线程就结束了。它不会重新开始。哦,我没看到,谢谢!为了实现这个解决方案,我尝试输入boo=false;x、 开始。。。x未被识别为线程对象。我认为这可能与对象的生命有关。但我不确定。你不能重新启动线程,你需要保持外循环,只有当boo为真时,它才会进入内循环