Issue
i'm a beginner developing in kotlin * android studio. i have 2 fragments in my app: a main fragment and a settings fragment. the two share a viewmodel. heres what i'm trying to accomplish:
- app launches, takes you to main fragment
- user clicks settings button, takes you to settings fragment
- user alters settings (preferences stored in shared viewmodel)
- user returns to main fragment, UI of main fragment is altered based on which settings were selected
i have completed steps 1-3 and am trying to implement 4. i am thinking i should override onResume() in my main fragment and implement UI changes there. first off, is this a good idea? if so, how can i access my UI elements from onResume()? any guidance is appreciated
Solution
I believe both of your fragments are living in the same activity in which case using a shared ViewModel
is not a bad idea.
Having said that, for settings it might be a good idea to save them in SharedPrefences
if they are primitive small sized data (String, int etc..)
You are right about overriding onResume()
to change your UI. Since you are going to make those changes from your fragment you should override onViewCreated()
and inside onViewCreated()
you can access your UI elements like this, for example:
val textView = activity.findViewById<TextView>(R.id.my_textview)
Or, you can bind your ViewModel
directly into your layout in that case you don't even have to override anything. You can read further about that here
Answered By - Tahir Ferli
Answer Checked By - David Marino (JavaFixing Volunteer)