Android 更新UI的方法汇总
程序员文章站
2024-03-04 18:08:06
1、activity的 runonuithread
textview = (textview) findviewbyid( r.id.tv );
new th...
1、activity的 runonuithread
textview = (textview) findviewbyid( r.id.tv ); new thread(new runnable() { @override public void run() { runonuithread(new runnable() { @override public void run() { textview.settext( "更新ui了"); } }); } }).start();
android activity runonuithread() 方法使用
2、handler sendemptymessage()
package lib.com.myapplication; import android.os.handler; import android.os.message; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.widget.textview; public class mainactivity extends appcompatactivity { private textview textview ; handler handler = new handler( ) { @override public void handlemessage(message msg) { super.handlemessage(msg); textview.settext( "ui更新了"); } }; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); textview = (textview) findviewbyid( r.id.tv ); new thread(new runnable() { @override public void run() { try { thread.sleep( 2000 ); } catch (interruptedexception e) { e.printstacktrace(); } handler.sendemptymessage( 2 ) ; } }).start(); } }
3、handler post()
package lib.com.myapplication; import android.os.bundle; import android.os.handler; import android.support.v7.app.appcompatactivity; import android.widget.textview; public class mainactivity extends appcompatactivity { private textview textview ; handler handler = new handler(); @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); textview = (textview) findviewbyid( r.id.tv ); new thread(new runnable() { @override public void run() { try { thread.sleep( 2000 ); } catch (interruptedexception e) { e.printstacktrace(); } handler.post(new runnable() { @override public void run() { textview.settext( "ui更新了"); } }) ; } }).start(); } }
4、view post()
textview = (textview) findviewbyid( r.id.tv ); new thread(new runnable() { @override public void run() { try { thread.sleep( 2000 ); } catch (interruptedexception e) { e.printstacktrace(); } textview.post(new runnable() { @override public void run() { textview.settext( "ui更新了"); } }) ; } }).start();
总结:
1、其实上面的四种方式都可归结于一种方式:handler 用于android线程之间的通信。
2、为什么android要求只能在ui线程进行ui操作? 主要还是为了避免多线程造成的并发的问题。在单线程操作ui是安全的。
以上所述是 给大家介绍的android 更新ui的方法汇总的相关知识,希望对大家有所帮助,如果大家有疑问欢迎给我留言,小编会及时回复大家的!
下一篇: Java代理模式详细解析