Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 안드로이드 앱에서 XML 파일 활용해 애니메이션 만들기 – 단계별 가이드

이 튜토리얼에서는 Kotlin을 사용해 안드로이드 앱에서 XML 파일로 애니메이션을 만드는 방법을 단계별로 알아봅니다. XML 기반 애니메이션은 복잡한 로직 없이도 깜빡임(Blink), 확대(Zoom) 같은 효과를 손쉽게 구현할 수 있어 코드를 깔끔하게 유지하는 데 큰 도움이 됩니다.


1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하고, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.

2단계: 레이아웃 작성 (activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 이 레이아웃에는 화면 중앙의 TextView와 하단의 Zoom, Blink 버튼 두 개가 배치되어 있습니다.

<?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:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:textColor="@android:color/holo_purple"
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Have a Wonderful day!"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:layout_above="@id/buttonBlink"
android:id="@+id/buttonZoom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Zoom" />
<Button
android:id="@+id/buttonBlink"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Blink" />
</RelativeLayout>

3단계: MainActivity.kt 코드 작성

src/MainActivity.kt에 아래 코드를 추가합니다. 핵심은 AnimationUtils.loadAnimation() 메서드로 res/anim 폴더의 XML 애니메이션을 불러온 뒤, 버튼 클릭 이벤트에서 startAnimation()으로 TextView에 애니메이션을 적용하는 것입니다.

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
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity(), Animation.AnimationListener {
private lateinit var textView: TextView
private lateinit var buttonZoom: Button
private lateinit var buttonBlink: Button
private lateinit var zoom: Animation
private lateinit var blink: Animation
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
buttonZoom = findViewById(R.id.buttonZoom)
buttonBlink = findViewById(R.id.buttonBlink)
blink = AnimationUtils.loadAnimation(applicationContext, R.anim.blink)
blink.setAnimationListener(this)
zoom = AnimationUtils.loadAnimation(applicationContext, R.anim.zoom)
zoom.setAnimationListener(this)
buttonZoom.setOnClickListener {
textView.visibility = View.VISIBLE
textView.startAnimation(zoom)
}
buttonBlink.setOnClickListener {
textView.visibility = View.VISIBLE
textView.startAnimation(blink)
}
}
override fun onAnimationStart(animation:Animation) {}
override fun onAnimationEnd(animation1:Animation) {}
override fun onAnimationRepeat(animation:Animation) {}
}

4단계: 애니메이션 리소스 파일 생성

먼저 안드로이드 리소스 디렉터리인 anim 폴더를 생성하고(res 폴더 우클릭 → New → Android Resource Directory → Resource type에서 anim 선택), 그 안에 애니메이션 리소스 파일을 추가한 후 아래 코드를 입력합니다.

blink.xml – 깜빡임 효과

alpha 태그로 투명도를 반복적으로 변화시켜 텍스트가 깜빡이는 효과를 줍니다. repeatCount를 infinite로 설정해 무한 반복됩니다.

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

zoom.xml – 확대 효과

scale 태그를 사용해 중심점(pivotX, pivotY = 50%)을 기준으로 크기를 1배에서 3배까지 확대합니다. fillAfter=true로 설정하면 애니메이션이 끝난 후에도 마지막 상태가 유지됩니다.

<?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>

5단계: AndroidManifest.xml 설정

마지막으로 androidManifest.xml에 아래 코드를 추가합니다. MainActivity가 앱 실행 시 시작 액티비티(LAUNCHER)로 등록되어 있어야 정상적으로 동작합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
<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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 Run(실행) 아이콘Kotlin으로 안드로이드 앱에서 XML 파일 활용해 애니메이션 만들기 – 단계별 가이드을 클릭하세요. 실행 옵션 목록에서 연결된 모바일 기기를 선택하면, 실제 기본 화면에서 아래와 같이 애니메이션 결과를 확인할 수 있습니다.

Kotlin으로 안드로이드 앱에서 XML 파일 활용해 애니메이션 만들기 – 단계별 가이드

Kotlin으로 안드로이드 앱에서 XML 파일 활용해 애니메이션 만들기 – 단계별 가이드