본문 바로가기
안드로이드 자바

[Java][Android] TranslateAnimation을 활용한 텍스트 이동 애니메이션

by teamnova 2024. 12. 18.
728x90

안녕하세요, 

 

오늘은 TranslateAnimation을 활용하여 텍스트를 이동하는 애니메이션 예제를 만들어 보겠습니다. 

 

TranslateAnimation은 Android에서 뷰를 X축과 Y축 방향으로 이동시키는 애니메이션 효과를 구현할 때 사용하는 클래스 입니다.

 

 

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // TextView와 Button을 연결
        TextView textView = findViewById(R.id.textView);
        Button button = findViewById(R.id.button);

        // 버튼 클릭 리스너 설정
        button.setOnClickListener(v -> {
            // TranslateAnimation 생성
            TranslateAnimation animation = new TranslateAnimation(
                    0, // 시작 x 위치
                    300, // 끝 x 위치 (px 기준으로 이동)
                    0, // 시작 y 위치
                    300 // 끝 y 위치
            );

            animation.setDuration(1000); // 애니메이션 지속 시간 (밀리초)
            animation.setFillAfter(true); // 애니메이션 종료 후 상태 유지

            // TextView에 애니메이션 적용
            textView.startAnimation(animation);
        });
    }
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="틱스트 입니다."
        android:textSize="18sp"
        android:layout_marginBottom="20dp"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="텍스트 이동" />

</LinearLayout>

 

 

시연 영상입니다.