Issue
How to let the dataBinding viewModel accessible on onOptionsItemSelected method.
class TestFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// viewModel
val viewModelFactory = TestViewModelFactory(
...
)
val viewModel = ViewModelProvider(
this, viewModelFactory).get(TestViewModel::class.java)
// dataBinding
val binding = FragmentTestBinding.inflate(inflater)
binding.lifecycleOwner = this
binding.viewModel = viewModel
return binding.root
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId) {
R.id.test_menu_item -> {
this.findNavController().navigate(
TestFragmentDirections
.actionTestFragmentToAnotherTestFragment(
...
)
)
viewModel.onNavigated() // How to access the viewModel here
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
Solution
Ok, declare lateinit global variable which is accessable for whole class
private lateinit var viewModel : TestViewModel
Now initialize viewModel with factory in onCreate():
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// factory
val viewModelFactory = TestViewModelFactory()
// viewModel
viewModel = ViewModelProvider(this, viewModelFactory).get(TestViewModel::class.java)
}
So the whole code looks like :
class TestFragment : Fragment() {
private lateinit var viewModel : TestViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// factory
val viewModelFactory = TestViewModelFactory()
// viewModel
viewModel = ViewModelProvider(this, viewModelFactory).get(TestViewModel::class.java)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// dataBinding
val binding = FragmentTestBinding.inflate(inflater)
binding.lifecycleOwner = this
binding.viewModel = viewModel
return binding.root
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId) {
R.id.test_menu_item -> {
this.findNavController().navigate(
TestFragmentDirections.actionTestFragmentToAnotherTestFragment()
)
viewModel.onNavigated() // How to access the viewModel here
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
Answered By - Rajasekhar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.