Reputation: 172
I currently have an interface that's implemented in the MainActivity that allows communication with the NumberFragment. The onCountClicked is the method in NumberFragment receiving the id of the item click.
Question
How can I send the onCountClicked position to the NumberFragmentViewModel every time an item is clicked?
Note: Using databinding & recycleview
Main Activity
val newFragment = NumberFragment()
val args = Bundle()
args.putInt(NumberFragment().onCountClicked(data).toString(),data.toInt())
newFragment.arguments = args
Number Fragment
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val sleepTrackerViewModel =
ViewModelProviders.of(
this, viewModelFactory).get(NumberViewModel::class.java)
setHasOptionsMenu(true)
binding.setLifecycleOwner(this)
binding.sleepTrackerViewModel = sleepTrackerViewModel
//Observes for any changes on database and updates the UI
sleepTrackerViewModel.dbCount.observe(this, Observer {dbCount ->
dbView.text = dbCount.number.toString()
})
return binding.root
}
fun onCountClicked(position: Long) {
Log.i("NumberF" , "------------->" + position)
}
Upvotes: 1
Views: 85
Reputation: 391
You can just simply create a method in the viewModel that receives that position and updates the value of the live data. I would do it like this:
private val _idItemClicked = MutableLiveData<Int>()
val idItemClicked: LiveData<Int> = _idItemClicked
fun setIdItemClicked(id: Int) {
_idItemClicked.value = id
}
Now you call the function setIdItemClicked to set a new value.
Upvotes: 1