赞
踩
更新ui的四种方式:getactivity.runonuithread;handler.post;handler.sendmessage;view post
handler.post:
public class Main3Activity extends AppCompatActivity { TextView textView; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main3); textView=(TextView)findViewById(R.id.text3); new Thread(){ @Override public void run() { super.run(); try { Thread.sleep(1000); handler.post(new Runnable() { @Override public void run() { textView.setText("ok"); } }); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } }handler.sendmessage:
public class Main3Activity extends AppCompatActivity { TextView textView; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); textView.setText("ok 2"); } }; public void handler2(){ handler.sendEmptyMessage(1); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main3); textView=(TextView)findViewById(R.id.text3); new Thread(){ @Override public void run() { super.run(); try { Thread.sleep(1000); handler2(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } }
public class Main3Activity extends AppCompatActivity { TextView textView; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; private void updateUI(){ runOnUiThread(new Runnable() { @Override public void run() { } }); } public void handler2(){ handler.sendEmptyMessage(1); } private void viewUI(){ textView.post(new Runnable() { @Override public void run() { textView.setText("ok 2"); } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main3); textView=(TextView)findViewById(R.id.text3); new Thread(){ @Override public void run() { super.run(); try { Thread.sleep(1000); viewUI(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } public void handler1(){ handler.post(new Runnable() { @Override public void run() { textView.setText("ok"); } }); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。