2011-10-23 36 views
0

当我按下按钮一次,while循环停止,并显示消息,但是当我再次按下时,while循环将不会再次开始(我知道这是因为runnable中的消息未显示)。代码只能有条件工作?

此外,线程中的组合while(!boo)和boo = true;在按钮中不会产生任何结果。

我会做什么错?我把布尔boo =真;外onCreate,所以我不认为这是问题...

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(); 
    } 

} 
+0

感谢您的编辑! – user947659

回答

0

当boo为false您的线程刚刚结束。它不会重新开始。

+0

哦,没有看到,谢谢!为了实现这个解决方案,我试着把boo = false; x.start(); ... x不被识别为一个Thread对象。我认为这可能与对象的生活有关......但我不确定。 – user947659

+0

你不能重新启动一个线程,你需要保持外部循环,如果boo为真,只会进入内部循环 – roni

+0

很有意义,谢谢! – user947659