Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there isDestroyed() for Fragment?

Activity has isDestroyed(), but I can't find the counterpart for Fragment.

I could override onDestroyed() to set a flag for myself but I assume there's an existing solution.

I'm trying to check whether a fragment is destroyed or not in a network response before updating UI in the fragment.

Any help will be greatly appreciated. Thanks!

like image 269
Vincent Avatar asked Apr 06 '16 22:04

Vincent


People also ask

Does fragment have onCreate?

onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.

How do I know if a fragment is destroyed?

Since all fragments are destroyed if the activity is destroyed, a simple answer could be calling getActivity(). isDestroyed() returning true if the activity is destroyed, therefore the fragment is destroyed.

What does the onCreateView () method return if a fragment doesn't have any?

These files contain only the onCreateView() method to inflate the UI of the fragment and returns the root of the fragment layout. If the fragment does not have any UI, it will return null.

How do you know if a fragment is visible?

fragment:fragment:1.1. 0 you can just use onPause() and onResume() to determine which fragment is currently visible for the user. onResume() is called when the fragment became visible and onPause when it stops to be visible.


1 Answers

You can create a Fragment as your parent of other fragments and use following code to check is destroyed functionality.

public abstract class ASafeFragment extends Fragment
{
    protected boolean isSafe()
    {
        return !(this.isRemoving() || this.getActivity() == null || this.isDetached() || !this.isAdded() || this.getView() == null);
    }
...
} 

or

public static boolean isSafeFragment( Fragment frag )
{
    return !(frag.isRemoving() || frag.getActivity() == null || frag.isDetached() || !frag.isAdded() || frag.getView() == null );   
}
like image 114
Hesam Avatar answered Sep 18 '22 08:09

Hesam