The function of the project is to achieve the Click Button progress bar by 10% increments, using the way is handler
The following code is the code in Mainactivity.java
PackageCom.example.progressbarhandler;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.ProgressBar; Public classMainactivityextendsActivity {//Declaration VariablesProgressBar bar =NULL; Button Startbutton=NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); //gets the object that represents the control based on the ID of the space, not the button to set the listenerBar =(ProgressBar) Findviewbyid (R.id.bar); Startbutton=(Button) Findviewbyid (R.id.startbutton); Startbutton.setonclicklistener (NewButtonlistener ()); } classButtonlistenerImplementsonclicklistener{@Override Public voidOnClick (View v) {//TODO auto-generated Method Stubbar.setvisibility (view.visible); Updatebarhandler.post (Updatethread); } } //using anonymous inner classes to write the Handmessage method in handlerHandler Updatebarhandler =NewHandler () { Public voidhandlemessage (Message msg) {bar.setprogress (MSG.ARG1); //Thread QueueUpdatebarhandler.post (Updatethread); } }; //A thread class that declares by using anonymous inner classesRunnable Updatethread =NewRunnable () {inti = 0; Public voidrun () {System.out.println ("Begin Thread"); I= i + 10; //get a Message object, the message class is provided by the Android operating systemMessage msg =Updatebarhandler.obtainmessage (); //set the value of the arg1 parameter of the MSG object to I, passing the message with the two members of Arg1 and Arg2MSG.ARG1 =i; Try{ //Set current display sleep 1 secondsThread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } //adding a Msg object to the message queueupdatebarhandler.sendmessage (msg); if(i = = 100){ //if the value of I is 100, the thread object is removed from the handleupdatebarhandler.removecallbacks (Updatethread); } } };}
The following code is the code in Activity_main.xml
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:id= "@+id/linearlayout1"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "Vertical"Tools:context= "${relativepackage}.${activityclass}" > <ProgressBar Android:id= "@+id/bar"style= "? Android:attr/progressbarstylehorizontal"Android:layout_width= "200DP"Android:layout_height= "Wrap_content"android:visibility= "Gone"/> <Button Android:id= "@+id/startbutton"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Start"/></linearlayout>
Android Learning Note--progressbarhandler