I would like to know how to access the variables of an activity from its fragment.
I will give an example to clarify my doubt:
Suppose I have an activity with a global variable called ventanaFragmentoAbierta
, and I want when the fragment opens one of its layouts it puts its value to true
and the activity finds out in real time (I'd like to work on onBackPressed()
it based on this).
In
Activity
it you define your method to modify the variable:and you access it from
Fragment
it like this:It is done this way since defining a public variable in one
Activity
can lead to problems if you have another Activity with the same public variable, you must ensure access to the Class method to modify its variable.define an interface
In your fragment you define an interface and make it throw an exception if the activity does not implement it
When you need to notify your activity you call your fragment's interface like this:
On the other hand your activity will implement the interface
And when your fragment calls the method you do what you want in your activity, which will be notified
More info: https://developer.android.com/training/basics/fragments/communicating.html#Implement
To access a variable of an activity from a fragment as you call it, I would tell you that it is wrong. I mean that what you are really looking for is to obtain a variable from a class, for this you only have to add
static
to the variable that you want to access from another class for example...you have to initialize since calling another class will get the value unless it has been altered in the course. Now to call from another class you would just have to do this.
and so you would get the value of that variable