Android編程實現(xiàn)使用handler在子線程中更新UI示例
本文實例講述了Android編程實現(xiàn)使用handler在子線程中更新UI。分享給大家供大家參考,具體如下:
MainActivity代碼:
package com.example.ui;
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;
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_main);
textView = (TextView) findViewById(R.id.textView);
new Thread(){
@Override
public void run() {
super.run();
try {
Thread.sleep(2000);
handler.post(new Runnable() {
@Override
public void run() {
textView.setText("ok");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.ui.MainActivity">
<TextView
android:textSize="40sp"
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android線程與消息機制用法總結(jié)》、《Android開發(fā)入門與進階教程》、《Android調(diào)試技巧與常見問題解決方法匯總》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對大家Android程序設計有所幫助。
相關(guān)文章
android實現(xiàn)關(guān)閉或開啟移動網(wǎng)絡數(shù)據(jù)
本篇文章是對android實現(xiàn)關(guān)閉或開啟移動網(wǎng)絡數(shù)據(jù)進行了詳細的分析介紹,需要的朋友參考下2013-06-06
Android 中RecyclerView頂部刷新實現(xiàn)詳解
這篇文章主要介紹了Android 中RecyclerView頂部刷新實現(xiàn)詳解的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-10-10

