首页 > 编程语言 > 详细

在子线程中更新UI,只能使用Handler

时间:2016-05-18 15:58:29      阅读:189      评论:0      收藏:0      [点我收藏+]
package com.pingyijinren.test;

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{
    public static final int UPDATE_TEXT=1;
    private TextView textView;
    private Button button;

    private Handler handler=new Handler(){
      public void handleMessage(Message msg){
          switch(msg.what){
              case UPDATE_TEXT:
                  textView.setText("HelloWorld");
                  break;
              default:
                  break;
          }
      }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=(TextView)findViewById(R.id.textView);
        button=(Button)findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable(){
                    @Override
                    public void run(){
                        Message message=new Message();
                        message.what=UPDATE_TEXT;
                        handler.sendMessage(message);
                    }
                }).start();
            }
        });
    }
}

 

在子线程中更新UI,只能使用Handler

原文:http://www.cnblogs.com/zqxLonely/p/5505404.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!