在子线程中更新UI

运行截图
这里写图片描述
MainActivity.java

package csdn.example.com.notification.AndroidThreadTest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import csdn.example.com.notification.R;

public class Main8Activity extends AppCompatActivity implements View.OnClickListener {

    //异步消息处理机制
    public static final int UPDATA_TEXT = 1;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPDATA_TEXT:
                    //在这里可以进行UI操作
                    textView.setText("Nice to meet you");
                    break;
                default:
                    break;
            }
        }
    };
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main8);
        textView = (TextView) findViewById(R.id.change_text);
        Button changeText = (Button) findViewById(R.id.change_text);
        changeText.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.change_text:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = UPDATA_TEXT;
                        handler.sendMessage(message); //将Message对象送出去
                    }
                }).start();
                break;
            default:
                break;
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/change_text"
        android:text="Change Text"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text"
        android:layout_centerInParent="true"
        android:text="Hello world"
        android:textSize="20sp"
        />
</RelativeLayout>
posted @ 2017-07-25 12:21  Philtell  阅读(74)  评论(0)    收藏  举报