Android4.1新機能特集:ActivityOptions APIを利用する


AndroidではActivityを起動する際、ズームや独自にカスタムしたアニメーションを付加して起動することができます。

Android 4.1では、Activity起動時に実行したいアニメーションを指定する場合に、ActivityOptions APIを使用することでstartActivityのようなActivityを起動するためのメソッドを利用してアニメーションを付加することができます。

ActivityOptionsクラスは、Activityを起動するときに表示したいアニメーションのタイプによって、次のようなメソッドが用意されています。
[table “262” not found /]

続きで実装方法を見てみましょう。

スケールアップアニメーションでActivityを起動する

今回は先ほどの表にて紹介したmakeScaleUpAnimation()メソッドを利用したサンプルを紹介します。

以下のはサンプルの画面遷移の様子です。1枚目は遷移前、3枚目は遷移後です。遷移途中の2枚目の画像に、うっすらスケールアニメーション中のActivityが見えているのがわかると思います。

  

ソースコードは以下の通りです。
■MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class MainActivity extends Activity {
 
    Intent intent;
    ActivityOptions mActivityOptions;
 
    @TargetApi(16)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intent = new Intent(this,AnimationActivity.class);
        Button button = (Button)findViewById(R.id.button1);
 
        mActivityOptions = ActivityOptions.makeScaleUpAnimation(button,0,0,button.getWidth(),button.getHeight());
        button.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View arg0) {
                Bundle bundle = mActivityOptions.toBundle();
                startActivity(intent,bundle);
            }
        });
    }
}

14行目でmakeScaleUpAnimation()メソッドを使用しています。makeScaleUpAnimation()を含む冒頭の表に示した3つの各メソッドは、ActivityOptionsクラスのインスタンスを返します。
makeScaleUpAnimation()メソッドの各引数は以下の通りです。
[table “263” not found /]

19行目でtoBundle()メソッドを用いて、生成したActivityOptionsクラスのインスタンスからBundleを生成しています。
生成したBundleを、startActivity()メソッドの第2引数に指定すると、次のActivityが前出の図のようにスケールアニメーションで起動します。
なお、アニメーション後のサイズは画面サイズとなります。