Package WHT. android. loading; import android. app. activity; import android. graphics. drawable. animationdrawable; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. widget. imageview; import android. widget. textview; public class mainactivity extends activity {public animationdrawable frameanimation; Public textview TV; Public imageview IV; Pub LIC Boolean flag = false; Public handler = new handler () {public void handlemessage (Message MSG) {stopanimation () ;};@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. donghua); IV = (imageview) findviewbyid (R. id. imgeview); IV. setbackgroundresource (R. anim. loading); frameanimation = (animationdrawable) iv. getbackground (); Frameanimation. setoneshot (true); // The last shot stops when it is true} public void stopanimation () {flag = true; system. out. println (FLAG); frameanimation. stop (); IV. setvisibility (view. gone); TV = (textview) findviewbyid (R. id. text); TV. settext ("started successfully! ");} Public void onwindowfocuschanged (Boolean hasfocus) {super. onwindowfocuschanged (hasfocus); frameanimation. start (); New thread (New runnable () {@ override public void run () {// todo auto-generated method stub try {thread. sleep (2000); // Why does the main thread not run handler during thread sleep. sendmessage (message. obtain ();} catch (interruptedexception e) {// todo auto-generated Catch Block E. printstacktrace ();}}}). start ();}}
Here, the thread is created in oncreate and then sleep. A problem occurs, that is, the interface is not displayed.
The interface is fully displayed and can be used only when onwindowfoucoschanged is used.
Another point is that the interface can only be changed in the main UI thread. Therefore, we need to implement the handler mechanism for communication.
Another aspect of the use of animation is the compilation of XML.
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false"> <item android:drawable="@drawable/loader_frame_1" android:duration="300" /> <item android:drawable="@drawable/loader_frame_2" android:duration="300" /> <item android:drawable="@drawable/loader_frame_3" android:duration="300" /> <item android:drawable="@drawable/loader_frame_4" android:duration="300" /> <item android:drawable="@drawable/loader_frame_5" android:duration="300" /> <item android:drawable="@drawable/loader_frame_6" android:duration="300" /> </animation-list>
This includes the image of each frame and the duration.