Activity.runOnUiThread(Runnable)简单介绍

来源:互联网 发布:淘宝假冒申诉 编辑:程序博客网 时间:2024/05/16 12:09

利用Activity.runOnUiThread(Runnable)把更新ui的代码创建在Runnable中,然后在需要更新ui时,把这个Runnable对象传给Activity.runOnUiThread(Runnable)。 Runnable对像就能在ui程序中被调用。如果当前线程是UI线程,那么行动是立即执行。如果当前线程不是UI线程,操作是发布到事件队列的UI线程。

public class TestActivity extends Activity {    Button btn;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.handler_msg);        btn = (Button) findViewById(R.id.button);        btn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                new Thread(new Runnable() {                    @Override                    public void run() {                        // 模拟耗时的操作。                        try {                            Thread.sleep(1000);                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                        // 更新主线程UI                        TestActivity.this.runOnUiThread(new Runnable() {                            @Override                            public void run() {                                btn.setText("更新完毕!");                            }                        });                    }                }).start();            }        });    }}


0 0
原创粉丝点击