본문 바로가기

Android

[Android] Translate Animation과 클릭 이벤트

Translate Animation이 적용된 View의 Click 이벤트 발생 위치가 생각과 달라 포스팅을 합니다.

anim/anim_right.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- fillAfter속성을 통해 Animation이 끝났을 때 상태를 유지합니다 -->
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:duration="500">
    <translate
        android:fromXDelta="0"
        android:toXDelta="100%" />
</set>

layout/activity_main.xml

...

<ImageView
    android:id="@+id/img"
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:background="@drawable/ripple_common"
    android:clickable="true"
    android:focusable="true"
    app:srcCompat="@drawable/ic_arrow_forward" />
<!-- Animation이 적용될 ImageView -->
    
...

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private ImageView mImg;
    private Animation rightAnim;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImg = findViewById(R.id.img);
        rightAnim = AnimationUtils.loadAnimation(this, R.anim.anim_right);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mImg.startAnimation(rightAnim);
    }
}

흰색 원이 터치 위치입니다. Ripple로 터치유무를 표시합니다.

기존의 View위치를 터치하였을 때 이벤트가 발생하는 모습입니다.

이동된 View에서 이벤트를 발생시키기 위해 ObjectAnimator을 사용했습니다.

MainActivity.java

    @Override
    protected void onResume() {
        super.onResume();
//        mImg.startAnimation(rightAnim);
        mImg.post(() -> {
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mImg, "translationX", 0, mImg.getWidth());
            objectAnimator.setDuration(500);
            objectAnimator.start();
        });
    }