Android 更新UI的方法汇总
1、Activity的runOnUiThread
textView=(TextView)findViewById(R.id.tv);
newThread(newRunnable(){
@Override
publicvoidrun(){
runOnUiThread(newRunnable(){
@Override
publicvoidrun(){
textView.setText("更新UI了");
}
});
}
}).start();
androidActivityrunOnUiThread()方法使用
2、HandlersendEmptyMessage()
packagelib.com.myapplication;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.widget.TextView;
publicclassMainActivityextendsAppCompatActivity{
privateTextViewtextView;
Handlerhandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
super.handleMessage(msg);
textView.setText("Ui更新了");
}
};
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.tv);
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
Thread.sleep(2000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
handler.sendEmptyMessage(2);
}
}).start();
}
}
3、Handlerpost()
packagelib.com.myapplication;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.support.v7.app.AppCompatActivity;
importandroid.widget.TextView;
publicclassMainActivityextendsAppCompatActivity{
privateTextViewtextView;
Handlerhandler=newHandler();
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.tv);
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
Thread.sleep(2000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
handler.post(newRunnable(){
@Override
publicvoidrun(){
textView.setText("Ui更新了");
}
});
}
}).start();
}
}
4、viewPost()
textView=(TextView)findViewById(R.id.tv);
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
Thread.sleep(2000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
textView.post(newRunnable(){
@Override
publicvoidrun(){
textView.setText("Ui更新了");
}
});
}
}).start();
总结:
1、其实上面的四种方式都可归结于一种方式:handler用于Android线程之间的通信。
2、为什么android要求只能在UI线程进行UI操作?主要还是为了避免多线程造成的并发的问题。在单线程操作UI是安全的。
以上所述是给大家介绍的Android更新UI的方法汇总的相关知识,希望对大家有所帮助,如果大家有疑问欢迎给我留言,小编会及时回复大家的!