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的方法汇总的相关知识,希望对大家有所帮助,如果大家有疑问欢迎给我留言,小编会及时回复大家的!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下