Search code examples
androidkotlinviewmodelandroid-jetpack

How do set Imageview Animation with use of viewmodel android kotlin


I have one imageView animation, so when i rotate screen it start again. How do i use that with viewModel.

Here is code

lateinit var img = ImageView

img = findViewById(R.id.img)
Img.animate().translationY(600F).setDuration(2000).setStartDelay(2000)

Solution

  • ViewModel holds data, but it should not hold a reference to a View.

    You could place a boolean in the ViewModel that is true, and after the animation you set its value to false. If you then turn your phone and the boolean value remains false, so it would not animate again.

    You will have something like this:

    img = findViewById(R.id.img);
    
    if (vm.getBooleanValue()) {
        img.animate().translationY(600F).setDuration(2000).setStartDelay(2000);
        vm.setBooleanValue(false);
    }