温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在子线程中更改主线程中的控件的信息,在子线程中用toast

发布时间:2020-06-25 03:50:00 来源:网络 阅读:380 作者:秋寒526 栏目:开发技术

一丶在子线程中不允许更改主线程中的控件的信息,也不允许在子线程中用toast,我们要更改的话

(1)消息机制:使用handler

    (由主线程调用)

    在主程序中Handler handler = new Handler(){

    public void handleMessage(Message msg){

            int type = msg.what ;//拿到msg的类型,再判断
            switch (type) {
                case SUCCESS:
                    //拿到信息
                    String info  = (String)msg.obj ;
                   //
                    break;
    
                case FAILED:
                    //拿到信息
                    String faild  = (String)msg.obj ;
                    Toast.makeText(MainActivity.this, faild, 0).show() ;
                    break;
                case ERROR:
                    //拿到信息
                    String error  = (String)msg.obj ;
                    Toast.makeText(MainActivity.this, error, 0).show() ;
                    break;
            }

};

};

而在子线程中要设置Message  msg;

msg.what(设置类型)

msg.obj(设置内容)然后发送:handler.sendMessage(msg);

(2)常见消息处理api:
  runOnUiThread(runnable): 在ui主线程中运行
  playAtTime() : 在某个时间运行
  playDelay(): 延时运行

例:public class MainActivity extends Activity {

    private TextView tvinfo ;
    
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            System.out.println("接收到了消息");
            tvinfo.setText((String)msg.obj) ;
        };
    } ;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tvinfo = (TextView) findViewById(R.id.tvinfo) ;
    }
    public void click(View view){ 
        handler.postDelayed(new Runnable() { 
            @Override
            public void run() {
                Message msg = Message.obtain() ;
                msg.obj = "哈哈哈,我改变了UI上的内容" ;
                handler.sendMessage(msg) ;
            }
        }, 3000) ;   
    }
}

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI