Dispatching Key Events to Fragments on Android
Every piece of my article has a story behind it. While developing a Camera app, I wanted the user to be able to take photos as well by pressing either the volume up key or the volume down key. There are a couple of ways that we can do this but we will go with activity to fragment communication using a shared viewModel.
We will have an activity that hosts a fragment and they both share a single ViewModel. Our ViewModel will hold a LiveData value for holding the integer value for the key up event and we will initialize its value to -1.
In our Activity, we will override Activity.onKeyUp() event, and whenever it is either of the volume key presses, we will set the value of the event by calling SharedViewModel.setEvent().Note that we initialize the viewModel in the activity using the by viewModels delegate.
We overrode onKeyUp and not onKeyDown because onKeyDown is called multiple times when the user presses and holds the button while onKeyUp is dispatched only once.
In the fragment hosted by the activity, we will get the ViewModel attached to the activity by using the by activityViewModels() delegate. Next, we will observe the value of the key event whenever it changes to see the appropriate key pressed and we take the appropriate action like taking a photo.
What happens is that since the activity and the fragment share the same instance of the ViewModel, when the call to the onKeyUpEvent is called in in the activity, the value is passed to the shared ViewModel and thus there is a change in the value of the keyEvent.
Note
The fragment-ktx and activity-ktx dependencies are required for the by delegates to work.
I hope you learned something new or improved on your learning. Leave some comments and please share.