If i have an Activity A which extends a base activity BA then i am able to safely access any variable in activity BA from activity A.What i am using now contains an activity A which includes a fragment F. Now from this fragment i want to access all variables of A in the same manner,just like i did above and if not is there a safe way of doing it other than making it available through public methods.
Or is there a way i can copy over the variables in the base activity to a base fragment so its available in all activities and fragments.
How to pass a variable from Activity to Fragment in Android? This example demonstrates how do I pass a variable from activity to Fragment in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
How to send a variable from Activity to Fragment in Android using Kotlin? This example demonstrates how to send a variable from Activity to Fragment in Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
The key difference, that emerges from the definitions, is that the fragment depends on an activity to exist, and so it represents only a part of the user interface. Instead, the activity can be considered like the container under which all other UI components (fragments included) will be placed.
It can be useful if you starts activity with fragment in xml, and would like to control somehow fragment's onCreate () behavior. Show activity on this post. Show activity on this post.
A good way for implementing it is to use an interface, as the official documentation suggests.
To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity.
So, basically inside your fragment you define an interface like this:
public interface MyListener {
public void onAction();
}
and define (still in the fragment) a field of type MyListener
MyListener mCallback;
Then you can set this listener using the onAttach(Activity)
method:
mCallback = (MyListener) activity;
Now, each time you want call from your fragment a method in the activity you can use the callback:
mCallback.onAction();
Of course, your Activity need to implement the interface, otherwise you will get an exception while casting your activity to MyListener.
So, just do:
public class MyActivity extends Activity implements MyFragment.MyListener {
@Override
public void onAction() {
// some stuff
}
}
For more details take a look at the documentation about communication between fragments
If VARIABLE_NAME
is a variable in you activity ACTIVITY_NAME
and can be accessed from outside Activity ACTIVITY_NAME
Then use this code:
((ACTIVITY_NAME)this.getActivity()).VARIABLE_NAME //this refers to your fragment
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