Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ending a Fragment

So I've about got down how to open a fragment. Here is my predicament. I have a list of the elements (periodic table elements) that is next to my view. When you select an element it shows it's information.

My problem is that I need to be able to remove the view from the (what we'll call details fragment) and remove it from the stack that way I don't have a huge memory backup.

How do I remove it from the stack when a new fragment is called to replace it?

like image 553
Joshua Sutherland Avatar asked Mar 17 '11 00:03

Joshua Sutherland


People also ask

How do you stop a fragment?

If you are using dynamic fragments, set up via a FragmentTransaction , you could run a transaction to replace() the old fragment with the new one.

How do I destroy fragments after replace?

To remove (so destroy) these fragments, you can call: You need to use findFragmentById for Fragment from XML file. And then find this in the MainActivity on click listener. I've added this to the OnClickListener but it always returns 'null' for the fragment I want to remove.

How do you 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 is fragment and its lifecycle?

Each Fragment instance has its own lifecycle. When a user navigates and interacts with your app, your fragments transition through various states in their lifecycle as they are added, removed, and enter or exit the screen.


1 Answers

You can remove a fragment using the #remove() method of FragmentTransaction. This method also removes the view from the container it has been attached to.

However, from the fragments documentation:

Stopped: The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed.

If you've added that fragment to the back stack it is not going to be killed until the activity gets killed.

like image 128
mgv Avatar answered Oct 27 '22 11:10

mgv