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)
CodePudding user response:
There are two ways you can solve this problem:
- Use the viewmodel
- Use onSaveInstanceState ()
Is. The second method is not suitable for heavy and large data and it is better to use the first method for your purpose.
viewmodels are not rebuilt when your UI is restarted, which is why you see the same UI as the previous UI in the output.
You can see how to implement viewmodels in Android by viewing the codelab below:
You can read more information about viewmodels from the link below: https://developer.android.com/topic/libraries/architecture/viewmodel
CodePudding user response:
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 could set the value of the boolean (in the Viewmodel) to false. If you then turn your phone the boolean value remains false, so it would not animate again.
so 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);
}