AndroidのView表示アニメーション

半透明のActivityを下からスライドさせて開く、というのをやりたくなった。
Activityのアニメーションで検索すると、大体ActivityのテーマのwindowAnimationStyleを設定する方法が出てくるようだ。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyTheme" parent="android:Theme">   
		<item name="android:windowAnimationStyle">@style/Animation.MyAnimation</item> 
    </style>
</resources>

しかし、この方法はランチャーから起動する時など無視されることが多々ある。自分はランチャーから起動したときも下からせりあがってきて欲しいので、今回の件には使えない。

幸い、現在開発中のアプリは透明のActivityに半透明のviewを貼りつける構成になっているので、以下の方針を立てた。

  • Activityが完全に透明であれば、windowAnimationStyleの影響を受けない。
  • ルートのviewを最初は非表示にしておき、Activityの起動後にアニメーション表示させる。

やってみた

あらかじめルートviewのvisibilityをinvisibleに設定しておき非表示にする。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/main"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:visibility="invisible"
        >
</layout>

そしてアニメーションを定義。
anim/open_main_screen.xml

<translate xmlns:android="http://schemas.android.com/apk/res/android"
	android:fromYDelta="100%"
	android:toYDelta="0%"
	android:duration="200"
	android:fillAfter="true"
	>
</translate>

translateは直線移動のアニメーション。fromYDelta、toYDeltaで開始/終了Y座標(絶対座標でも%でも可)を、durationでアニメーションにかける時間(msec)を設定する。さらにfillAfterでアニメーション終了後の状態を維持する。


仕上げにjavaのコードから呼び出し。

Animation animation = AnimationUtils.loadAnimation(activity,R.anim.open_main_screen);
View rootView = activity.findViewById(R.id.main);
rootView.startAnimation(animation);

思った通りに動作した。Acitivtyが閉じるときにルートviewを非表示にしておけば完璧。

おまけ

XMLを使いたくなければ全てJavaで記述することもできる。

TranslateAnimation animation = 
        new TranslateAnimation(
    		Animation.RELATIVE_TO_PARENT, 0.0f,
    		Animation.RELATIVE_TO_PARENT, 0.0f, 
    		Animation.RELATIVE_TO_PARENT, 1.0f,
    		Animation.RELATIVE_TO_PARENT, 0.0f);
animation.setDuration(200);
animation.setFillAfter(true);
rootView.startAnimation(animation);

Animation.RELATIVE_TO_PARENTを指定すればXMLのときと同じく%で指定できる。(1.0 == 100%)