Home » Android » java – Android: how can fragment take a global variable of Activity

java – Android: how can fragment take a global variable of Activity

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have an activity with a global variable int x, how can a fragment get the current value of variable x of its activity ?

How to&Answers:

Either set the var as public static, or use

((MyActivity)getActivity()).getX()

Answer:

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.

Answer:

Kotlin version:

(activity as MyActivity).x

Answer:

***In your Activity
==================
Bundle args = new Bundle();
args.putInt("something", Whatever you want to pass);
fragA.setArguments(args);

In your Fragment
==================
 Bundle args = getArguments();
//whatever you want to get ,get it here.
//for example integer given     
    int index = args.getInt("index", 0);