代码只能有条件地运作?

时间:2011-10-23 04:52:54

标签: java android if-statement while-loop

当我按下按钮一次时,while循环停止,并显示消息,但是当我再次按下时,while循环将不会再次启动(我知道这一点,因为不显示runnable中的消息)。

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

我可能做错了什么?我把布尔boo = true;外面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();
    }

}

1 个答案:

答案 0 :(得分:0)

当boo为false时,你的线程就会结束。它不会重新开始。

相关问题