Handler--消息处理机制


页面布局 content_main.xml




    




主程序HandlerTest .用Handler处理图片显示切换效果
package com.eson.handler ;




import android.os.Bundle ;

import android.os.Handler ;

import android.os.Message ;

import android.support.v7.app.AppCompatActivity ;

import android.widget.ImageView ;




import java.util.Timer ;

import java.util.TimerTask ;




public class HandlerTest extends AppCompatActivity {




    //定义周期性显示图片的ID

    int [] imageIds= new int []{

            R.drawable. java,

            R.drawable. javaee ,

            R.drawable. ajax ,

            R.drawable. classic

    } ;

    int currentImageId = 0;

    @Override

    protected void onCreate (Bundle savedInstanceState) {

        super .onCreate(savedInstanceState) ;

        setContentView(R.layout. activity_main );




        final ImageView show= (ImageView) findViewById(R.id. show );

        final Handler myHandler= new Handler(){

            @Override

            public void handleMessage (Message msg) {




                if (msg. what ==0x1233 ){

                    //动态修改所显示的图片

                    show.setImageResource( imageIds [currentImageId ++% imageIds. length ]);

                }




            }

        };

        //定义一个定时器,让该计时器周期性地执行指定任务

        new Timer().schedule( new TimerTask() {

            @Override

            public void run () {

                //发送消息

                myHandler.sendEmptyMessage( 0x1233 );

            }

        }, 0 ,1200 ) ;

    }

}

你可能感兴趣的:(Handler--消息处理机制)