First of all what you want is not a good approach, and what i am suggesting is just an idea, its not tested and recommended but can do your work
Create class BaseFragment and extend you each class with Base Fragment
must override its getView()
In these approached you have to remove root view as a class member getView returns the same
public class BaseFragment extends Fragment {
@Nullable
@Override
public View getView() {
super.getView();
}
}
Now you can do it in two ways
Create boolean
in BaseFragment
with private access boolean canAccess = true;
with no getter and setter and change definition of your getView()
to
public BaseFragment() {
canAccess = false;
}
@Nullable
@Override
public View getView() {
if(canAccess)
return super.getView();
return
null;
}
You must call super()
for your every child constructors, now if you access getView
inside the class canAccess
is true so you will get actual view otherwise you will get null.
As per documentation
Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
if provided @return The fragment's root view, or null if it has no layout.
Second option is much simplest
@Nullable
@Override
public View getView() {
try {
throw new Exception("Who called me?");
} catch (Exception e) {
String className = e.getStackTrace()[1].getClass().getCanonicalName();
if (className.equals(YourParentActivity.class.getCanonicalName()))
return null;
else
return super.getView();
}
}