当前位置: 移动技术网 > 移动技术>移动开发>Android > 安卓开发笔记(十九):异步消息处理机制实现更新软件UI

安卓开发笔记(十九):异步消息处理机制实现更新软件UI

2019年04月01日  | 移动技术网移动技术  | 我要评论

主界面代码

<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".mainactivity">

   <button
       android:id="@+id/change"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="改变内容"/>
   <textview
       android:id="@+id/text"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerinparent="true"
       android:text="你好,世界!"
       android:textsize="20sp"/>

</relativelayout>

主活动代码:

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;

public class mainactivity extends appcompatactivity implements view.onclicklistener{
    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("遇见你真好");
                    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);
        changetext.setonclicklistener(this);
    }
    public void onclick(view v)
    {
        switch (v.getid())
        {
            case r.id.change:
                new thread(new runnable() {
                    @override
                    public void run() {
                        message message=new message();
                        message.what=update_text;
                        handler.sendmessage(message);

                    }
                }).start();
                break;
                default:
                    break;
        }

    }
}

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网