Android 動態物件的進出動畫 (入場/出場) - ViewFlipper

Android 中, 可以利用 ViewFlipper 做物件的入場動畫 / 出場動畫,

實現步驟, 如下 :

檔案結構 :


main.xml :
 檔案內容
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="@+id/widget10"
android:layout_width="300px"
android:layout_height="400px"
android:layout_x="5px"
android:layout_y="5px"
android:src="@drawable/a2"
/>
<ViewFlipper
android:id="@+id/viewFlipperWidget"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</AbsoluteLayout>

tom_anim.xml :
 檔案內容
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Y 軸從 238 移動到 38, 歷時 1000 毫秒 -->
<translate android:fromYDelta="238"
android:toYDelta="38"
android:duration="1000" />
<!-- 從 透明 到 不透明, 歷時 1000 毫秒 -->
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="1000" />
</set>

tom_anim_out.xml :
 檔案內容
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Y 軸從 38 移動到 238, 歷時 1000 毫秒 -->
<translate android:fromYDelta="38"
android:toYDelta="238"
android:duration="1000" />
<!-- 從 不透明 到 透明, 歷時 1000 毫秒 -->
<alpha android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="1000" />
</set>

Java 部分程式碼 :
 程式碼
public class helloWorld extends Activity {

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// 要使用 findViewById, 一定要使用 layout / *.xml 做為使用者介面
setContentView( R.layout.main );

// 取得 UI 介面中的 View 物件
// 取得 View 物件後,再透過轉換成實際的物件

ViewFlipper vf = (ViewFlipper)this.findViewById(R.id.viewFlipperWidget);

// 建立 ImageView
Drawable dd = this.getResources().getDrawable( R.drawable.icon );
ImageView iv = new ImageView( this);
iv.setImageDrawable( dd );

// 建立 TextView
TextView tv = new TextView( this );
tv.setText( "Hello, Tom" );

// 哪些 View 物件要加入到 ViewFlipper 動畫內
vf.addView( iv, new ViewGroup.LayoutParams( 75, 70 ));
vf.addView( tv );

// 設定 ViewFlipper 的進出動畫配置
vf.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.tom_anim));
vf.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.tom_anim_out));

// 動畫開始
vf.startFlipping();
}
}

範例結果 :








Related Posts Plugin for WordPress, Blogger...