Reputation: 415
I can pass an AppCompatActivity through a function parameter from a Fragment. But I can't figure out how to check which fragment pass inside that function. How instanceof checking could be possible.
Suppose, I have two fragments.
Both Can pass AppCompatActivity like this.
StaticAccess.checkSignal((AppCompatActivity) OptionsFragment.this.getActivity())
Or
StaticAccess.checkSignal((AppCompatActivity) HomeFragment.this.getActivity())
Inside StaticAccess Class...
public class StaticAccess{
public static void checkSignal(final AppCompatActivity context){
//how to check context is instanceof which fragment when
//if(context instanceof OptionFragment) not comparable
}
}
Upvotes: 0
Views: 134
Reputation: 742
You can't compare Activity
with a Fragment
(for obvious reasons), they are totally separate things. A Fragment
is not bound to any particular Activity
, it can be triggered from any Activity
.
When you pass OptionsFragment.this.getActivity()
, you are not passing the Fragment
, you are passing the Activity
that the Fragment
is currently in. So the context
in your checkSignal()
function is of the Activity
.
There are a couple of ways to go about it, and it all depends on what implementation you use in your app.
For example, if you have a patter where OptionsFragment
and HomeFragment
are always called from separate activities, Then for example if OptionsFragment
was triggered from Activity1
and HomeFragment
from Activity2
in your checkSignal
function you would do something like if (context instanceof Activity1) { // Do stuff }
etc. However, this would be a bad and not scalable approach in my opinion.
Now, if your patter is such that the checkSignal
function is only called from Fragments
, then you can change the constructor to static void checkSignal(final Fragment context)
, call the function from the fragment like StaticAccess.checkSignal(this)
, and check for the type like this if (context instanceof HomeFragment) { // Do stuff }
. However, this too is a bad and not scalable approach.
If I were you, I would create an enum
with the different possible signal types, and pass that as the parameter. This will remove the dependency of whether you call it from an Activity
, Fragment
, or wherever you want (especially since it is static
, it can be called from anywhere). Something like this:
public enum SignalSource {
HOME,
OPTIONS
}
public class StaticAccess{
public static void checkSignal(SignalSource source){
if (source == SignalSource.HOME) {
// Do something...
} else if (source == SignalSource.OPTIONS) {
// Do something...
}
}
}
// Call it like this from anywhere
StaticAccess.checkSignal(SignalSource.HOME)
Upvotes: 1