Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】XMLファイルを使ってアニメーションを作成する方法をわかりやすく解説

この記事では、AndroidアプリにおいてXMLファイルを使用してアニメーションを作成する方法を、実際のコード例とともに段階的に解説します。View Animation(Tween Animation)は、res/animディレクトリに配置したリソースファイルとして定義できるため、フェードインやズーム、点滅といった演出をJava側のコードをほとんど書かずに実現できるのが特徴です。

ステップ1:新規プロジェクトの作成

Android Studioを起動し、メニューから「File」⇒「New Project」を選択して新しいプロジェクトを作成します。ウィザードに従って必要な情報を入力し、プロジェクトのセットアップを完了させてください。

ステップ2:レイアウトファイルの作成(activity_main.xml)

res/layout/activity_main.xmlに以下のコードを記述します。画面中央にはアニメーション対象となるTextViewを、画面下部にはアニメーションを開始するためのButtonを配置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:padding="4dp"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:textSize="24sp"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Have a Wonderful day!"
        android:layout_centerInParent="true"
        android:id="@+id/textView" />
    <Button
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Animation"/>
</RelativeLayout>

ステップ3:アニメーションリソースファイルの作成

続いて、res配下に新しいAndroidリソースディレクトリ「anim」を作成し、その中に以下のアニメーション定義ファイルを追加します。

Myanim.xml(フェードイン)

透明度(alpha)を0.0から1.0へ変化させるフェードインアニメーションの定義例です。android:fillAfter="true"を指定することで、アニメーション終了後も最終状態が維持されます。

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android" android:fillAfter="true">
    <alpha
        android:duration="1000"
        android:fromAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="1.0" />
</set>

zoom.xml(ズーム)

中心(pivotX/pivotY=50%)を基準に、スケールを1倍から3倍へ拡大するズームアニメーションの定義例です。

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android" android:fillAfter="true">
    <scale
        android:duration="1000"
        android:fromXScale="1"
        android:fromYScale="1"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="3"
        android:toYScale="3"></scale>
</set>

blink.xml(点滅)

repeatCount="infinite"repeatMode="reverse"を組み合わせることで、往復しながら無限に繰り返す点滅アニメーションを定義できます。

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="600"
        android:repeatMode="reverse"
        android:repeatCount="infinite"/>
</set>

ステップ4:MainActivity.javaの実装

src/MainActivity.javaに以下のコードを記述します。AnimationUtils.loadAnimation()でアニメーションリソースを読み込み、ボタンがタップされたタイミングでTextViewに対してstartAnimation()を呼び出します。また、Animation.AnimationListenerを実装することで、アニメーションの開始・終了・繰り返しの各タイミングで任意の処理を追加することも可能です。

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements
Animation.AnimationListener {
    TextView textView;
    Button button;
    Animation animation;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.button);
        animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink);
        animation.setAnimationListener(this);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setVisibility(View.VISIBLE);
                textView.startAnimation(animation);
            }
        });
    }
    @Override
    public void onAnimationStart(Animation animation) {
    }
    @Override
    public void onAnimationEnd(Animation animation1) {
    }
    @Override
    public void onAnimationRepeat(Animation animation) {
    }
}

ステップ5:androidManifest.xmlの確認

androidManifest.xmlに以下のコードを記述します。特別な権限は不要ですが、MainActivityがランチャーとして登録されていることを確認しておきましょう。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
        </activity>
    </application>
</manifest>

アプリの実行と動作確認

それではアプリを実行してみましょう。ここでは、実機のAndroidスマートフォンがパソコンに接続されているものとします。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーにある「Run」アイコンをクリックします。実行対象として接続した端末を選択すると、端末の画面にアプリが表示されます。

【Android】XMLファイルを使ってアニメーションを作成する方法をわかりやすく解説

【Android】XMLファイルを使ってアニメーションを作成する方法をわかりやすく解説

ボタンをタップすると、画面中央のTextViewに対してblink.xmlで定義した点滅アニメーションが再生されます。R.anim.zoomR.anim.myanimなど、読み込むリソースを変更するだけで、同じ仕組みでさまざまなアニメーションを試せるので、ぜひ各種パラメータを調整しながら動きを確認してみてください。

  1. 【Android】ExpandableListViewでマルチレベル(階層型)リストを作成する方法

    Androidアプリ開発では、カテゴリごとに項目を整理したマルチレベル(階層型)リストを実装したいケースが多くあります。本記事では、ExpandableListViewを使用して、親項目(グループ)をタップすると子項目が展開される2階層リストを作成する方法を、サンプルコードとともにステップごとに解説します。 ExpandableListViewとは? ExpandableListViewは、親項目(グループ)と子項目からなる2階層構造のリストを表示できるAndroid標準ウィジェットです。設定画面やFAQなど、階層的なデータをわかりやすく見せたい場面で活用できます。今回はスポーツ選手の一覧を例

  2. 【Android】XMLファイルを使ってアニメーションを作成する方法をわかりやすく解説

    この記事では、AndroidアプリにおいてXMLファイルを使用してアニメーションを作成する方法を、実際のコード例とともに段階的に解説します。View Animation(Tween Animation)は、res/animディレクトリに配置したリソースファイルとして定義できるため、フェードインやズーム、点滅といった演出をJava側のコードをほとんど書かずに実現できるのが特徴です。 ステップ1:新規プロジェクトの作成 Android Studioを起動し、メニューから「File」⇒「New Project」を選択して新しいプロジェクトを作成します。ウィザードに従って必要な情報を入力し、プロジェク