While循环在Android上不起作用

时间:2018-08-22 10:33:35

标签: java android

我需要延迟1秒显示数字。没有while循环,它可以工作,但是一旦我添加了while循环,它将在while循环结束后输出值。有人可以在这方面提供帮助。

int state = 0;
int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button=(Button)findViewById(R.id.b_main);
    textView =(TextView) findViewById(R.id.text_main);
    listView =(ListView) findViewById(R.id.t_main);
    arrayList=new ArrayList<String>();

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(state==0){
                state=1;
                try {
                    while(count<10) {
                        textView.setText("Start " + count++);
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                state=0;
                textView.setText("Stop " + count++);
            }
        }
    });
}

3 个答案:

答案 0 :(得分:1)

请勿在UI线程上调用Thread.sleep()。您需要将代码放在单独的线程中,然后使用runOnUiThread发布结果:

if(state==0){
    state=1;

    new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                while(count<10) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText("Start " + count++);
                        }
                    });

                    Thread.sleep(1000);
                    count++;
                } 
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
        }
    }).start();
}

答案 1 :(得分:0)

请勿使用Thread.sleep()。使用处理程序强制执行所需的延迟。

    final Handler handler = new Handler();
    final int delay1 = 1000; // adjust as needed


     handler.postDelayed(new Runnable() {
                public void run() {

                    // Code Block 1. Code here will be executed after 1000 millisec


                }
            }, delay1);


//  Code Block 2. Code here will be executed immediatelly ( before **Code Block 1** )

答案 2 :(得分:0)

在进行与时间有关的操作时,更好的方法是使用Sepal.Length。在主线程上使用CountDownTimer是不好的,因为线程休眠时Ui会卡住

以下是有关如何实现它的示例Thread.sleep()

CountDownTimer