https://kotlinlang.org logo
#android
Title
# android
s

Soundlicious

10/29/2018, 3:38 AM
Anyone working with mvrx here? i'm using it with Android Navigation Component to display a view with bottomNavigation and two fragment. i would like to share an id to those two fragments, but i can't access the activity that contain them... bit lost here with that framework 😥
s

Sam

10/29/2018, 4:14 AM
Try android-united
o

okarm

10/29/2018, 3:52 PM
I use it. What is your use case?
s

Soundlicious

10/30/2018, 2:08 AM
@okarm Right now i'm using Android Navigation component with two activity. The First one display a list of user and the second display with a bottomNavigationView two fragment giving details about that user. So when i select an user in the first activity, i give the id to my second activity and then i want to use that id to fetch the information online... problem, i don't know how to share that id from my 2nd activity to my fragments. My second activity only contain a HostNavigationFragment. When i try to do a getActivity, i only retrieve a FragmentActivity which is not my Activity at all... 🤔 But i'm probably out of the scope of the framework trying to use it like that
o

okarm

10/30/2018, 11:57 AM
@Soundlicious This has nothing to do with the Navigation component or MvRx. It's just plain old getting an ID from containing activity. You must cast the result of
getActivity()
to your concrete Activity type.
Copy code
// somewhere inside inside onCreateView, assuming the fragment's containing activity is an instance of ProfileDetailActivity

val userId = (activity as ProfileDetailActivity?)?.userId ?: -1
myViewModel.getUserDetail(userId)
//viewModel handles the case when userId == -1 and sets the state accordingly, otherwise fetches profile detail


// OR IF this fragment could be used inside multiple known Activities, use something like this:
val userId = activity?.let { activity ->
    when(activity) {
        is Activity1 -> activity.getIdFromActivity1() // will be smart cast to type Activity1 for you
        is Activity2 -> activity.getIdFromActivity2() //will be smart cast to type Activity2 for you
        else -> throw IllegalStateException("Containing activity is not of valid type! Actual type: ${activity::class.simpleName}")
    }
} ?: -1
4 Views