1. 程式人生 > >面試常客Handler詳細解析(更新UI的幾種方式)(六)

面試常客Handler詳細解析(更新UI的幾種方式)(六)

一共有:
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>