我們都知道在android中,常見的動畫模式有兩種:一種是幀動畫(frame animation),一種是補間動畫(tween
animation)。幀動畫是提供了一種逐幀播放圖檔的動畫方式,播放事先做好的圖像,與gif圖檔原理類似,就像是在放電影一樣。補間動畫可以實作view元件的移動、放大、縮小以及漸變等效果。
今天我們主要來模仿一下美團中加載資料時小人奔跑動畫的對話框效果,取個有趣的名字就是running man,奔跑吧,兄弟!話不多少,先上效果圖,讓各位大俠看看是不是你想要實作的效果,然後再決定是否往下閱讀,因為做為程式員我們的時間都很寶貴,畢竟還沒有女朋友呢?
(ps:因為技術原因,提供的動态圖效果不是很明顯,但在手機上運作是非常好的,有興趣的朋友可以下載下傳源碼看看。)
下面講講實作的原理,首先我們在項目的res目錄下建立一下anim檔案夾,然後建立一個xml檔案,添加如下代碼:
[html] view
plaincopy
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false" >
<item
android:drawable="@drawable/app_loading0"
android:duration="150"/>
android:drawable="@drawable/app_loading1"
</animation-list>
animation-list 是動畫清單,中間放很多的item 也就是組成幀動畫的圖檔,
android:drawable[drawable]//加載drawable對象
android:duration[long]//每一幀動畫的持續時間(機關ms)
android:oneshot[boolean]//動畫是否隻運作一次,true運作一次,false重複運作
寫好之後我們來看自定義一個對話框,來實作打開對話框時,自動加載奔跑的動畫。見代碼:
[java] view
/**
* @description:自定義對話框
* @author http://blog.csdn.net/finddreams
*/
public class customprogressdialog extends progressdialog {
private animationdrawable manimation;
private context mcontext;
private imageview mimageview;
private string mloadingtip;
private textview mloadingtv;
private int count = 0;
private string oldloadingtip;
private int mresid;
public customprogressdialog(context context, string content, int id) {
super(context);
this.mcontext = context;
this.mloadingtip = content;
this.mresid = id;
setcanceledontouchoutside(true);
}
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
initview();
initdata();
private void initdata() {
mimageview.setbackgroundresource(mresid);
// 通過imageview對象拿到背景顯示的animationdrawable
manimation = (animationdrawable) mimageview.getbackground();
// 為了防止在oncreate方法中隻顯示第一幀的解決方案之一
mimageview.post(new runnable() {
@override
public void run() {
manimation.start();
}
});
mloadingtv.settext(mloadingtip);
public void setcontent(string str) {
mloadingtv.settext(str);
private void initview() {
setcontentview(r.layout.progress_dialog);
mloadingtv = (textview) findviewbyid(r.id.loadingtv);
mimageview = (imageview) findviewbyid(r.id.loadingiv);
}
可以看到在代碼中,我們使用到一個imageview.post(runnable r)方法,因為幀動畫需要不斷的重畫,是以必須線上程中運作,否則隻能看到第一幀的效果,這和我們做遊戲的原理是一樣的,一個人物的走動,是有線程在控制圖檔的不斷重畫。
當然還有另外一個方法也能實作:
@override
public void onwindowfocuschanged(boolean hasfocus) {
// todo auto-generated method stub
manimation.start();
super.onwindowfocuschanged(hasfocus);
最後就是在activity中調用了,詳情:
customprogressdialog dialog =new customprogressdialog(this, "正在加載中",r.anim.frame);
dialog.show();
對于customprogressdialog這個自定義對話框類是封裝的比較好的,調用起來十分友善,你可以快速的替換成你想要的效果,隻需更改圖檔就可以了。
最後附上源代碼,還不夠了解的朋友可以下載下傳看看,希望對你有所幫助;
http://download.csdn.net/detail/finddreams/8401429