E
E
egotyner2016-05-06 19:48:25
Java
egotyner, 2016-05-06 19:48:25

How to access a class instance in the main activity from a fragment?

Tell me how to access, say, from a fragment to a class instance in the main activity? Let's say I have a certain class provider of some data in the activity class that I need to shove into the seekBar. If I was doing this in the activity class, I would just write findViewById(R.id.seekBar).setMax(myFooProvider.getMax()); - Well, roughly speaking. How can I do this in a fragment, if I need an instance of the provider class! store in the activity class, because when changing fragments, the provider instance is deleted from memory, along with the fragment, if I'm not mistaken. And the provider instance should work regardless of which fragment is currently active, because background actions take place in it.
Of course, I can do essentially the same thing in an activity, and not in a fragment
(I'm talking about this: findViewById(R.id.seekBar).setMax(myFooProvider.getMax()); ), and even tried, but since seekBar is in fragment A, when changing to fragment B, null reference flies here, because seekBak, As I understand it, it is unloaded from memory, or something like that. Check for null or fragment activity? Isn't it expensive for CPU time if, say, such a check takes place every 50 milliseconds? Or doesn't play much?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
belozerow, 2016-05-06
@egotyner

The interface is the surest way:
developer.android.com/intl/ru/training/basics/frag...
But it is also quite terrible when there are a lot of interfaces for one activity.
Don't use EventBus. It is needed only for exceptional situations, such as some kind of global changes - a purchase was made, a logout occurred, etc.
If you shove it everywhere, then it will quickly turn into hell. Moreover, you are just starting to develop judging by the question.

O
Oleg Gamega, 2016-05-06
@gadfi

or drop the interface (then in the fragment check if the activity implements this interface), or use the EventBus

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question