'Why ViewModel is still alive after I replaced fragment in Android?
I use BottomNavigation in Android,But,After I replace RotationFragment to ScaleFragment,Back to BottomNavigationFragment,RotationViewModel's rotation value always alive
MainActivity
class MainActivity : AppCompatActivity() {
lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navHostFragment = supportFragmentManager
.findFragmentById(binding.navHostFragment.id) as NavHostFragment
val navController = navHostFragment.navController
val configuration = AppBarConfiguration.Builder(binding.bottomNavigationView.menu).build()
NavigationUI.setupActionBarWithNavController(this, navController,configuration)
NavigationUI.setupWithNavController(binding.bottomNavigationView, navController)
}
}
RotationFragment
When image clicking,after rotation value add 100,use animator rotation image and save (rotation+100) to ViewModel rotation value,but,after switch ScaleFragment,back to RotationFragment RotationViewModel's rotation is 100 not 0
class RotationFragment : Fragment() {
private lateinit var viewBinding : RotationFragmentBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewBinding = RotationFragmentBinding.inflate(inflater, container, false)
return viewBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val viewModel = ViewModelProvider(this).get(RotationViewModel::class.java)
//viewBinding.imgRotationMood.rotation = viewModel.rotation.toFloat()
Log.d("onViewCreated", "onViewCreated: ${viewModel.rotation.toFloat()}")
val animatorMood = ObjectAnimator.ofFloat(viewBinding.imgRotationMood, "rotation", 0.0f,0.0f)
animatorMood.duration = 500
viewBinding.imgRotationMood.setOnClickListener {
if(!animatorMood.isRunning) {
animatorMood.setFloatValues(viewBinding.imgRotationMood.rotation,
viewBinding.imgRotationMood.rotation + 100)
viewModel.rotation = viewModel.rotation + 100
animatorMood.start()
}
}
}
}
RotationViewModel
class RotationViewModel : ViewModel() {
var rotation = 0
}
I trying use official BottomNavigation Template,get same result
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
