线程休眠后TextView不打印vlaue

时间:2015-09-02 11:46:33

标签: android multithreading

电视值设置为值1然后在5000之后它没有设置其值,显示应用

tv = (TextView) findViewById(R.id.textView1); 

    Thread  time = new Thread(){
        public void run(){
        try{
            tv.setText("Value 1");
            sleep(5000);
            tv.setText("Value 2");
        }
        catch ( InterruptedException e){
            e.printStackTrace();
        }finally{
            tv.setText("Value 3");
        }
        }
    };
    time.start(); 

3 个答案:

答案 0 :(得分:2)

你必须在主线程上运行处理UI的代码...它被称为UIThread ...除了处理UI之外,你可以在另一个线程上做任何事情

new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
    tv.setText....

}
});

答案 1 :(得分:2)

您应该调用Activity.runOnUiThread()从其他线程更新UI。

Thread t = new Thread() {
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv.setText("Value 1");
            }
        });
    }
};

使用Handler

Thread t =new Thread(){
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    tv.setText("Value 1");
                }
            });
        }
    }};

答案 2 :(得分:2)

您必须在runOnUiThread()方法中运行TextView更新方法。您的代码应如下所示:

Thread time = new Thread() {
    public void run() {
        try {

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    tv.setText("Value 1");
                }
            });

            sleep(5000);

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    tv.setText("Value 2");
                }
            });

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            tv.setText("Value 3");
        }
    }
};
time.start();