On an article for everyone to introduce how to send message data through handler object to the main thread, I think everyone must have mastered, this article I will be an example of the way for everyone to summarize the use of handler, example is through handler to achieve a picture automatically change the effect, Generally we are through the viewpage to achieve this effect, but this article we will learn how to achieve this effect through handler.
Before we start, we need to prepare several images to update the switch, so that we can put these pictures under the Res drawable-hdpi. With this we can begin our effect:
1. layout file:
<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Tools:context= "${relativepackage}.${activityclass}" > <ImageView Android:id= "@+id/imageview1"Android:layout_width= "300px"Android:layout_height= "300px"Android:layout_alignparenttop= "true"Android:layout_centerhorizontal= "true"Android:layout_margintop= "87DP"android:src= "@drawable/abc_ab_share_pack_holo_light"/> <Button Android:id= "@+id/stop"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_alignleft= "@+id/imgbutton"Android:layout_alignparenttop= "true"Android:layout_margintop= "36DP"Android:text= "Stop Switching"/></relativelayout>
2. Our Activity code:
Public classImgactivityextendsActivity {PrivateImageView ImageView; PrivateButton stop; PrivateHandler Handler =NewHandler (); Private intImageall [] ={r.drawable.download1, r.drawable.download2, r.drawable.download3}; Private intindex = 1; PrivateMyrunable myrunable =Newmyrunable (); @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.LAYOUT.ACTIVITY_IMG); Stop=(Button) Findviewbyid (r.id.stop); ImageView=(ImageView) Findviewbyid (R.ID.IMAGEVIEW1); Stop.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View arg0) {handler.removecallbacks (myrunable);//Stop Switching } }); Handler.postdelayed (myrunable,1000); } classMyrunableImplementsrunnable{@Override Public voidrun () {index= index%3; Imageview.setimageresource (Imageall[index]); Index++; Handler.postdelayed (myrunable,1000); } }}
Well, our example is complete, simply introduce the code for you:
index = index%3;: Control our picture switch
handler.postdelayed (myrunable, +);: Execute our myrunable object every 1s
Handler.removecallbacks (myrunable);: Remove our Myrunable object, stop execution
OK our example effect has been introduced for everyone, we can write their own, very interesting yo!
Handler summary of the Android threading process