I have an activity with a global variable int x, how can a fragment get the current value of variable x of its activity ?
So, to pass data from the MotherActivity to such a Fragment you will need to create private Strings/Bundles above the onCreate of your Mother activity - which you can fill with the data you want to pass to the fragments, and pass them on via a method created after the onCreate (here called getMyData()).
Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.
I became a believer in Fragments in my last application. Whether or not they are computationally faster, they feel faster because you can swap them in and out basically instantaneously, including full support for the back stack if you do it right (call addToBackStack() on the transaction, or something very similar).
It can't exist independently. We can't create multi-screen UI without using fragment in an activity, After using multiple fragments in a single activity, we can create a multi-screen UI. Fragment cannot be used without an Activity.
Either set the var as public static
, or use
((MyActivity)getActivity()).getX()
Using a public static variable isn't the best way to communicate between an activity and a fragment. Check out this answer for other ways:
The Android documentation recommends using an interface when the Fragment wants communicate with the Activity. And when the Activity wants to communicate with the Fragment, the Activity should get a reference to the Fragment (with findFragmentById) and then call the Fragment's public method.
The reason for this is so that fragments are decoupled from the activity they are in. They can be reused in any activity. If you directly access a parent Activity or one of its global variables from within a fragment, you are no longer able to use that fragment in a different Activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With