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();
    


     

    学会勇敢
  • 相关阅读:
    Asp.net Treeview 客户端选中效果实现 (初级)
    MYSQL生成日历表,通常在做报表的时候需要用来生成一个临时表,用来左连接等。
    写了一个抽奖类,感觉还不错,可以适合各种变化
    将系统的内部类:HttpValueCollection 移到自己的系统中,使其能方便的解析id=1&name=张三&sex=男这样的字符串参数 querystring
    指定某个文件的创建 修改 访问时间
    Reqeust["keyname"] 的读取顺序
    pku1463 Strategic game
    pku1947 Rebuilding Roads
    pku1848 Tree
    pku1056 IMMEDIATE DECODABILITY
  • 原文地址:https://www.cnblogs.com/Sir-Lin/p/4799079.html
Copyright © 2011-2022 走看看