问题
Can I detect whether the Fragment I am going to call is already called or created so that I can reuse it instead of recreating it?
回答1:
The fragments have isVisible() method .
if(fragment.isVisible()){
//your code.//
}
By this you can see if the fragment is already created or not.
回答2:
Test if onCreateView
has been called
public abstract class SubFragment extends Fragment
{
protected boolean onCreateViewCalled = false;
public boolean hasOnCreateViewBeenCalled()
{
return onCreateViewCalled;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup Container, Bundle state){
onCreateViewCalled = true;
return null;
}
}
for more details please read here
回答3:
You could use findFragmentByTag()
:
Finds a fragment that was identified by the given tag either when inflated from XML or as supplied when added in a transaction. This first searches through fragments that are currently added to the manager's activity; if no such fragment is found, then all fragments currently on the back stack are searched.
So your code should look like this:
val tag = "MyFragment"
// add a tag to transaction
supportFragmentManager.beginTransaction()
.replace(R.id.frame, fragment, tag)
.commit()
// check if fragment exists by the given tag
var instance = supportFragmentManager.findFragmentByTag(tag)
if (fragment == null) {
instance = MyFragment.newInstance()
} else {
// reuse fragment instance
}
来源:https://stackoverflow.com/questions/58856484/can-i-detect-whether-fragment-is-already-created-or-called