在子线程中更新UI

       和许多其他的GUI库一样,Android的UI也是线程不安全的。也就是说,如果想要更新应用程序里的UI元素,则必须在主线程中进行,否则就会出现异常。

一、新建一个AndroidThreadTest项目,然后修改activity_main.xml中的代码。

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<Button
    android:id="@+id/change_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Change Text"/>


    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="hello world"
        android:textSize="20sp"/>
</RelativeLayout>

二、修改MainActivity中的代码

package com.example.yxp.xianchegn;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.security.MessageDigest;
import android.os.Handler;
import java.util.logging.LogRecord;

public class MainActivity extends Activity {

    private TextView text;
    public static final int UPDATE_TEXT = 1;

 private Handler handler = new Handler() {
        public void  handleMessage(Message msg){

            switch (msg.what){

                case UPDATE_TEXT:
                    text.setText("Nice to meet you");
                    break;
                default:
                    break;


            }




        }


 };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView)findViewById(R.id.text);
        Button changeText = (Button) findViewById(R.id.change_text);
        changeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = UPDATE_TEXT;
                        handler.sendMessage(message);

;
                    }
                }).start();
            }
        });

    }

}

三、效果

猜你喜欢

转载自blog.csdn.net/danwuxie/article/details/84400406