安卓学习-界面-事件-handler

安卓程序运行后,系统会产生一条主线程,如果在主线程里修改UI,则会照成冲突,因此安卓建议用handler来更改UI

1.4张图片定时变换

MainActivity.java

public class MainActivity extends Activity {

    ImageView imageView1;
    int index=0;
    
    int[] pics=new int[]{R.drawable.pic1,R.drawable.pic2,R.drawable.pic3};
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        imageView1=(ImageView)findViewById(R.id.imageView1);
        

        thread.start();
    
    }
    
    Thread thread=new Thread(){
        public void run() {
            try {
                while(true){
                    sleep(1000);
                    hand.sendEmptyMessage(12345);
                }

            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
    };

    Handler hand=new Handler(){

        public void handleMessage(Message msg) {
            if(msg.what==12345){
                imageView1.setImageResource(pics[index%3]);
                
                index=index+1;
            }

        }
    };
    
}
View Code

 

posted on 2014-11-01 14:06  weijj  阅读(112)  评论(0编辑  收藏  举报

导航