最近做個小應用需要用到動畫效果,組員已經實現了效果,拿過來修改下。
原理:動畫看起來的效果是圖片在移動,而且幾張圖片不停的在切換。
實現過程:
1、在res目錄下建立anim檔案夾,建立myfish.xml,把幾張圖片的切換動畫設定好:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false" > <item android:drawable="@drawable/xiaoyu2" android:duration="300"/> <item android:drawable="@drawable/xiaoyu0" android:duration="300"/> <item android:drawable="@drawable/xiaoyu1" android:duration="300"/></animation-list>
2、在main.xml中,給予myfish一個ID
<RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageButton android:id="@+id/myjellyfish" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true"/> <ImageButton android:id="@+id/myfish" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
3、在java檔案中調用:
private ImageButton mFish;//魚仔
添加移動動畫效果
public void Fish_StartAnimation() {// ////////////////*********小魚遊動**************///////////////////////mFish = (ImageButton) findViewById(R.id.myfish);AnimationDrawable fish_anim = new AnimationDrawable();mFish.setBackgroundResource(R.anim.my_fish);fish_anim = (AnimationDrawable) mFish.getBackground();fish_anim.start();AnimationSet fish_animset = new AnimationSet(true);TranslateAnimation swim_fishTr = new TranslateAnimation(300.0f,-850.0f, 0.0f, 0.0f);swim_fishTr.setDuration(30000);swim_fishTr.setRepeatCount(Animation.INFINITE);fish_animset.addAnimation(swim_fishTr);mFish.startAnimation(fish_animset);}
在需要調用動畫的地方調用Fish_StartAnimation()函數
Fish_StartAnimation();
這樣便實現了一邊移動一邊切換圖片的動畫效果。
另:關於 TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
裡面的參數要看你硬體螢幕的解析度了,代表螢幕中心是:X軸:0.0f,Y軸:0.0f