简体   繁体   English

如何在runnable上运行Textview

[英]How to run a Textview on runnable

I have this following code, the problem that i read is that you cannot place a textview inside a runnable method, how can i implement this one. 我有以下代码,我读到的问题是,您不能将textview放在可运行的方法内,我该如何实现这一点。

Thread UDPreceive;
    Handler handler = new Handler();
    void startListen() {
        UDPreceive = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while(true) {
                        String hey;
                        //TextView text22 = (TextView) findViewById(R.id.textView2);
                        int server_port = 9875;
                        byte[] message = new byte[255];
                        DatagramPacket p = new DatagramPacket(message, message.length);
                        DatagramSocket s = new DatagramSocket(server_port);
                        s.receive(p);
                        hey = new String(message, 0, p.getLength());
                        Log.d("MESSAGE: ", "Message is:" + hey);
                        //text22.setText(hey);
                        s.close();
                    }
                } catch (Exception e) {
                    System.err.println(e);
                    e.printStackTrace();
                }
            }

        });
        UDPreceive.start();

    }
textview.post(new Runnable() {    // Use the post method of the TextView
    public void run() {
       textview.setText(    // Update the Textview
            "some text"
        );
    }
});
Yo can also use 

runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                text22.setText(hey);
                            }
                        });

It will give you main thread access to render on UI.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM