Answer the question
In order to leave comments, you need to log in
Pattern for accessing the active instance of a class?
Please tell me some design pattern for accessing the active class instance. For example, in Android, you need to access some Activity or fragment from the service.
The only thing that comes to mind is a static field of the class, in which the reference to the object is written when it is created / active. But I think this is the wrong choice.
Answer the question
In order to leave comments, you need to log in
I advise you to read about Dependency Injection. There are good tools for working with this:
Dagger - an article on Habré about it
RoboGuice - an article on Habré about it
Perhaps this is exactly what you are looking for. If you need a fragment context, you can get it from the activity context. Activities can be obtained using DependencyInjection. This is done differently depending on the instrument.
FragmentManager fm = myActivity.getFragmentManager();
Fragment f = fm.findFragmentByTag("MyFragment");
TextView textView = (TextView) f.getView().findViewById(R.id.myTextView);
textView.setText("bla-bla");
As you wrote - we add a static field, i.e. pattern Singleton (Singleton)
in onCreate we assign instance = this;
and add the getInstance() method; which returns this field
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question