标签:
public class MainActivity extends Activity { private EditText UITxt; private Button updateUIBtn; private UIHandler UIhandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); UITxt = (EditText)findViewById(R.id.ui_txt); updateUIBtn = (Button)findViewById(R.id.update_ui_btn); updateUIBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub UIhandler = new UIHandler(); UIThread thread = new UIThread(); thread.start(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } private class UIHandler extends Handler{ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); Bundle bundle = msg.getData(); String color = bundle.getString("color"); UITxt.setText(color); } } private class UIThread extends Thread{ @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Message msg = new Message(); Bundle bundle = new Bundle(); bundle.putString("color", "黄色"); msg.setData(bundle); MainActivity.this.UIhandler.sendMessage(msg); } } }
更新后:
private class UIThread2 extends Thread { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { UITxt.setText("黄色"); } });
我的Android最佳实践之—— Android更新UI的两种方法:handler与runOnUiThread()
标签:
原文地址:http://www.cnblogs.com/scarecrow-blog/p/5768405.html