如何从Thread中textView.setText?

POM*_*ATu 13 multithreading android

我需要从线程中将文本设置为textView.所有代码都是在oncreate()中创建的

就像是

public TextView pc;

    oncreate(..) {
        setContentView(R.layout.main);
        pc = new TextView(context);
        Thread t =new Thread() {
            public void run() {
                pc.setText("test");
        }};
        t.start();
Run Code Online (Sandbox Code Playgroud)

这会导致我的应用崩溃.如何从线程设置文本?

big*_*nes 10

试试Activity.runOnUiThread().

Thread t = new Thread() {
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pc.setText("test");
            }
        });
    }
};
Run Code Online (Sandbox Code Playgroud)


Ted*_*opp 9

使用处理程序:

public TextView pc;
Handler handler = new Handler();
oncreate(..) {
    setContentView(R.layout.main);
    pc = new TextView(context);
    Thread t =new Thread(){
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    pc.setText("test");
                }
            });
        }
    }};
    t.start();
}
Run Code Online (Sandbox Code Playgroud)

但是你有另一个问题.pc指向不属于您的层次结构的视图.您可能希望findViewById在布局中使用TextView的id.