问题
In my custom view I have a Java class running a simple game. When the game is finished I'd like to display my DialogFragment
, but the getFragmentManager()
method seems to be undefined.
FragmentManager manager = getFragmentManager();
Finish finish = new Finish();
finish.show(manager, "done");
I've tried getting the manager through a Fragment
obj as:
Fragment fragment = new Fragment();
FragmentManager manager = fragment.getFragmentManager();
But that returns as null. I know it's a new Fragment
instance, but I'm not sure what value to give it. Any help would be much appreciated.
回答1:
if your view is attached to an Activity
then simply you can do
((Activity)getContext()).getFragmentManager();
or
((ActivityCompat)getContext()).getSupportFragmentManager();
and to be more safe please make sure you check against of the View Context
is instance of an Activity
by doing such:
if(getContext() instanceof Activity)// do something
and a better solution is, i had rely on a callback between the View
and the Activity
.
回答2:
I use that simple helper method:
fun getFragmentManager(context: Context?): FragmentManager? {
return when (context) {
is AppCompatActivity -> context.supportFragmentManager
is ContextThemeWrapper -> getFragmentManager(context.baseContext)
else -> null
}
}
回答3:
You can use this (in Kotlin):
if ((context as ContextThemeWrapper).baseContext is AppCompatActivity) {
//View is attached to an AppCompatActivity
} else {
//View is not attached to an AppCompatActivity
}
}
回答4:
For AndroidX
, you can try:
ContextThemeWrapper themeWrapper = (ContextThemeWrapper) getContext();
FragmentManager fm = ((AppCompatActivity) themeWrapper.getBaseContext()).getSupportFragmentManager();
As recommoned by @k0sh, instaceof
safety check is recommonded.
来源:https://stackoverflow.com/questions/36684553/accessing-fragmentmanager-in-a-custom-view-class