【发布时间】:2017-03-13 23:16:10
【问题描述】:
我不明白在程序运行期间如何使用处理程序来更新 TextView。我正在用这样的简单代码对其进行测试
public class MainActivity extends AppCompatActivity {
TextView text;
boolean isReady; //boolean to check a new Message
String update; //String to send to TextView
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView);
Handler handler = new MyHandler(); //defined down
MyHandlerThread thr = new MyHandlerThread(handler); //defined in other .class file
thr.start();
for(int i=0;i<100;i++){ //a simple for
if(i%2==0)
thr.setMessage(i + ": Divisible for 2");
else
thr.setMessage(i+": Not Divisible for 2");
}
}
private class MyHandler extends Handler { //inner class
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
if(bundle.containsKey("refresh")) {
String value = bundle.getString("refresh");
text.setText(value);
}
}
}}
这是线程代码
public class MyHandlerThread extends Thread {
private Handler handler;
private boolean isSent;
String text;
public MyHandlerThread(Handler handler) {
this.handler = handler;
isSent=false;
text="";
}
public void run() {
try {
while(true) {
if(isSent){
notifyMessage(text);
Thread.sleep(1000);
isSent=false;
}
}
}catch(InterruptedException ex) {}
}
public void setMessage(String str){
text=str;
isSent=true;
}
private void notifyMessage(String str) {
Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("refresh", ""+str);
msg.setData(b);
handler.sendMessage(msg);
}}
这段代码只打印最后一个预期的字符串“99: not divible for 2”
【问题讨论】:
标签: android multithreading textview android-handler