如何 运行 运行nable 上的 Textview
How to run a Textview on runnable
我有下面的代码,我读到的问题是你不能在可运行的方法中放置一个文本视图,我该如何实现这个。
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.
我有下面的代码,我读到的问题是你不能在可运行的方法中放置一个文本视图,我该如何实现这个。
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.