Android Study

Object Animator 이미지 이동시키기

85chong 2021. 9. 13. 14:12
728x90
반응형
SMALL

이미지 이동시키기

 

- 준비물 : 

ic_surfing , activity_main.xml , MainActivity.kt

 

 

- activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:id="@+id/rl_body"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <ImageView
        android:id="@+id/iv_surfing"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_surfing"/>

    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

- MainActivity.kt

class MainActivity : BaseActivity() {

    var mHandler = Handler()
    var mRunnable = Runnable{}
    lateinit var mImg:ImageView
    var mObjAnimY: ValueAnimator? = null
    var mObjAnimX: ValueAnimator? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mImg = findViewById(R.id.iv_surfing)
        startMoveImage(mImg,600f,9000f,10000L)
    }

    fun startMoveImage(imag1: ImageView, move_positionx:Float, move_positiony:Float, duration: Long){
        mRunnable = object :Runnable{
            override fun run() {
                //image1(Object)를 X축으로 이동시킨다.
                mObjAnimX = ObjectAnimator.ofFloat(imag1,"translationX",move_positionx)
                mObjAnimX?.duration = duration
                mObjAnimX?.start()

                //image1(Object)를 Y축으로 이동시킨다.
                mObjAnimY = ObjectAnimator.ofFloat(imag1,"translationY",move_positiony)
                mObjAnimY?.duration = duration
                mObjAnimY?.start()

                //Object 리스너
                mObjAnimY?.addListener(object :Animator.AnimatorListener{
                    override fun onAnimationStart(animation: Animator?) {
                        //Object 시작할때
                    }

                    override fun onAnimationEnd(animation: Animator?) {
                        //Object 끝났을때
                        mHandler.removeMessages(0)//Handler로 호출을 종료시켜준다.
                    }

                    override fun onAnimationCancel(animation: Animator?) {
                        //Object 취소 시켰을때(Object 멈추게 해준다 / pause 는 일시정지 후 다시 움직인다.)
                    }

                    override fun onAnimationRepeat(animation: Animator?) {
                        //Object 반복 될때(mObjAnimY?.repeat 을 사용하면 호출된다)
                    }

                })
                mHandler.postDelayed(mRunnable,duration)//시작만큼의 딜레이로 핸들러에 적용
            }
        }
        mHandler.post(mRunnable)//핸들러 시작
    }



}//class end

 

- 끝 -