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; public boolean flag = false; public Handler 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); //為真的時候最後一針會停下 } public void StopAnimation(){ flag = true; System.out.println(flag); frameAnimation.stop(); iv.setVisibility(View.GONE); tv = (TextView)findViewById(R.id.text); tv.setText("啟動成功!"); } 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); // 線程休眠時為什麼主線程也不運行 handler.sendMessage(Message.obtain()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } }
其中在onCreate 中建立了線程然後sleep,出現了一個問題,那就是介面沒有顯示出來
介面完全顯示出來要等到 onWindowFoucosChanged時才可以
還有一點,介面只能在UI主線程中更改,所以,我們要去實現handler機制來進行通訊。
關於animation的使用,還有一點就是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>
其中包括每一幀的圖片,和持續的時間。