개요
이 예제는 Android에서 뷰(View)의 배경색 변경을 부드러운 애니메이션 효과로 전환하는 방법을 보여줍니다. 핵심은 TransitionDrawable 클래스입니다. 여러 개의 ColorDrawable을 배열로 묶어 전달하면, 색상 간에 자연스러운 크로스페이드(cross-fade) 전환 효과를 손쉽게 만들 수 있습니다.
이번 예제에서는 버튼을 클릭하면 TextView의 배경색이 빨강 → 파랑 → 초록 순서로 2초에 걸쳐 서서히 변하도록 구현합니다.
구현 단계
1단계 — 새 프로젝트 생성
Android Studio를 실행한 뒤 File → New Project를 선택하고, 프로젝트 생성에 필요한 정보를 모두 입력하여 새 프로젝트를 만듭니다.
2단계 — 레이아웃 작성 (res/layout/activity_main.xml)
버튼 하나와 배경색이 변할 TextView 하나를 담은 기본 레이아웃입니다. 아래 코드를 res/layout/activity_main.xml 파일에 추가합니다.
<?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:id="@+id/relativeLayout"
android:padding="8dp"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:text="Animate background color"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/textView"
android:layout_centerInParent="true"
android:layout_marginBottom="15dp"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="36sp"
android:textStyle="bold"
android:text="Changing Background color of this view."
android:layout_centerInParent="true" />
</RelativeLayout>3단계 — 메인 액티비티 작성 (src/MainActivity.java)
버튼이 클릭되면 빨강, 파랑, 초록 세 가지 색상의 ColorDrawable 배열로 TransitionDrawable을 생성하고, 이를 TextView의 배경으로 설정한 뒤 startTransition() 메서드로 애니메이션을 시작합니다. 아래 코드를 src/MainActivity.java에 추가합니다.
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
textView = findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ColorDrawable[] colorDrawables = {new ColorDrawable(Color.RED),
new ColorDrawable(Color.BLUE), new ColorDrawable(Color.GREEN)};
TransitionDrawable transitionDrawable = new TransitionDrawable(colorDrawables);
textView.setBackground(transitionDrawable);
transitionDrawable.startTransition(2000);
}
});
}
}4단계 — 매니페스트 설정 (androidManifest.xml)
메인 액티비티가 정상적으로 등록되어 있는지 확인합니다. 아래는 완성된 AndroidManifest.xml 코드입니다.
<?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 아이콘을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면, 해당 기기에 앱이 설치되고 기본 화면이 표시됩니다.


핵심 포인트 정리
- TransitionDrawable: 여러 Drawable을 계층으로 쌓아두고, startTransition() 호출 시 첫 번째 레이어에서 마지막 레이어로 크로스페이드하는 클래스입니다.
- 지속 시간 조절: startTransition(2000)처럼 밀리초 단위 값을 인자로 넘기면 전환 속도를 자유롭게 조절할 수 있습니다.
- 역방향 재생: reverseTransition() 메서드를 사용하면 전환을 반대 방향으로 되돌릴 수도 있습니다.