Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 元件動畫(一):球的進入效果與多重插值器

編輯:Android 開發實例

本節實作一個「球進入」的動畫效果,讓多顆球以不同的運動曲線飛入畫面。

首先是寬高的取得。之所以要動態獲取螢幕寬高,是為了適應 Android 多樣的螢幕尺寸。雖然很多時候可以用 XML 裡的 dip 定位,但更多時候我們需要在程式碼中動態加入元件,而程式碼裡設定的數值都以 px 計算,這樣做出來的軟體或遊戲根本無法良好適配螢幕。因此若非透過 XML 配置而要動態解決,我的做法是將介面寬高各切分為若干份(切得越細,控制越精準,但管理也越費心),再依需要賦予寬與高。

動畫效果方面,這裡用到了一組插值器(Interpolator):

// 寬和高
private int width = 100;
private int height = 100;

//要給元件的動畫集合
private static final int[] INTERPOLATORS = {
 android.R.anim.accelerate_interpolator,
 android.R.anim.decelerate_interpolator,
 android.R.anim.accelerate_decelerate_interpolator,
 android.R.anim.anticipate_interpolator,
 android.R.anim.overshoot_interpolator,
 android.R.anim.anticipate_overshoot_interpolator,
 android.R.anim.bounce_interpolator };

每顆球會套用不同的插值器,呈現加速、減速、回彈、彈跳等多樣的運動效果。

元件配置 balls_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 android:orientation="horizontal">

 <LinearLayout android:layout_width="fill_parent"
 android:layout_height="wrap_content" android:orientation="horizontal"
 android:id="@+id/layout" android:paddingRight="35dip"></LinearLayout>

 <ImageView android:id="@+id/delete" android:scaleType="fitXY"
 android:src="@drawable/delete" android:layout_width="30dip"
 android:layout_height="30dip" android:layout_alignParentRight="true">
 </ImageView>
</RelativeLayout>

核心的 testBallSliding.java 程式碼:

public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.balls_item);

 width = getWindowManager().getDefaultDisplay().getWidth();
 height = getWindowManager().getDefaultDisplay().getHeight();

 LinearLayout layout = (LinearLayout) findViewById(R.id.layout);

 String[] buttons = list.split(" ");

 for (int i = 0; i < buttons.length; i++) {
 Button button = new Button(this);
 button.setPadding(2, 2, 2, 2);
 //這裡控制動畫的顯示位置
 Animation animation = new TranslateAnimation(width + 50, i * 40, 0, 0);
 //設定動畫的運動效果
 animation.setInterpolator(getApplicationContext(), INTERPOLATORS[i
 % INTERPOLATORS.length]);
 animation.setDuration(4000 - 50 * i);
 button.setAnimation(animation);

 button.setText(buttons[i]);
 button.setBackgroundResource(R.drawable.redball);

 ImageView delete = (ImageView) findViewById(R.id.delete);
 // 刪除的監聽
 // .........

 layout.addView(button,new LayoutParams(40, 40));
 }
}

這裡先以簡單的範例為後續內容做鋪墊。透過 TranslateAnimation 搭配不同的插值器與錯開的時間參數,就能讓每顆球以各具特色的曲線飛入畫面,營造生動的進場效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved