您的位置:首页 > 产品设计 > UI/UE

面试常客Handler详细解析(更新UI的几种方式)(六)

2016-03-07 09:39 561 查看
一共有:

UI主线程 activityd的runOnUiThread

handler post

handler sendMessage

view post

下面将我自己已经验证成功的代码贴出了,其实这些方法都是殊途同归,都是使用了handler,封装成message进行发送的:

主程序:

package com.example.handler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

public class FiveActivity extends Activity {

private TextView tv;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
tv.setText("ok2");
};
};

private void handle1(){
handler.post(new Runnable() {

@Override
public void run() {
tv.setText("ok");

}
});
}

private void handle2(){
handler.sendEmptyMessage(1);

}

private void updateUI(){
runOnUiThread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
tv.setText("ok3");
}
});
}

private void viewUI(){
tv.post(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
tv.setText("ok4");
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fiva);
tv = (TextView) findViewById(R.id.tv);

new Thread(){
public void run() {
try {
Thread.sleep(2000);
viewUI();

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();;
}

}


布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv"
android:textSize="40sp"/>

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: