zoukankan      html  css  js  c++  java
  • Handler

    Handler是什么,handler是android给我们提供用来更新UI的一套机制,也是一套消息处理机制,可以发送消息,也可以通过它处理消息。

    为什么使用Handler,Android在设计的时候。就封装了一套消息创建、传递、处理机制,如果不遵循这样的机制就没有办法更新UI消息,就会抛出异常信息,也就是说要遵守游戏规则。

    例1.handler循环执展示图片,

    private int images[] = {R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};
    private int index;

    private Handler handler = new Handler();    
    class MyRunnable implements Runnable{
            @Override
            public void run() {
                index ++;
                index = index% 4;
                imageView.setImageResource(images[index]);
                handler.postDelayed(myRunnable, 1000);
            }
            
        }
    private MyRunnable myRunnable = new MyRunnable();
    //在主线程中开始handler,开始循环
    handler.postDelayed(myRunnable, 1000);
    //停止handler
    handler.removeCallbacks(myRunnable);
     
    例2.在handler中接收message其实就是handler自己给自己发送的消息
    //定义一个class,用于handler发送消息
        class people{
            private int age;
            private String name;
            @Override
            public String toString() {
                return "people [age=" + age + ", name=" + name + "]";
            }
        }
    //handler接收消息和执行更新UI或其他的需要在主线程中完成的操作    
    private Handler handler = new Handler(){
            public void handleMessage(android.os.Message msg) {
                
                textView.setText(""+msg.obj);
            };
        };
    //在主线程中开辟一个新的线程
    new Thread(){
                public void run() {
                    try {
                        Thread.sleep(2000);
    //两种创建消息的方式
                        //Message message = new Message();
                        Message message = handler.obtainMessage();
                        message.arg1 = 88;
                        people peo = new people();
                        peo.age = 33;
                        peo.name ="22";
                        message.obj =peo; 
    //两种发送消息的方式
                        message.sendToTarget();
                        //handler.sendMessage(message);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                };
            }.start();
    


     

    学会勇敢
  • 相关阅读:
    idea 快捷键 记录
    Spring Boot 之注解@Component @ConfigurationProperties(prefix = "sms") 使用@ConfigurationProperties读取yml配置
    SpringData Jdbc
    设备树中指定的中断触发方式与request_irq中指定的触发方式不一致时,内核会使用哪种中断触发方式呢?
    设备树中的interrupts属性解析
    编译grub时报告"grub_script.yy.c:19:22: error: statement with no effect [-Werror=unused-value]"怎么处理?
    uefi是如何启动linux内核的?
    markdown中如何设置字体为红色?
    linux下如何查看磁盘分区所使用的文件系统格式?
    bootargs中的rootwait 与rootdelay有什么区别?
  • 原文地址:https://www.cnblogs.com/Sir-Lin/p/4799079.html
Copyright © 2011-2022 走看看