What is the null target in addToBackStack (null)?

I'm new to Andoid, and I created a fragment to replace the fragments programmatically.

I followed the guidance of Android developers.

I created a method called selectFrag and launched it by clicking a button:

 public void selectFrag(View view) { Fragment fr; if(view == findViewById(R.id.showsecond)) { fr = new secondfragment(); } else { fr = new firstfragment(); } FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.fragment_place,fr); ft.addToBackStack(null); ft.commit(); } 

The code works fine, and I understand everything except addToBackStack(null) .

I experimented and realized that this method consists in adding a fragment to the stack of the feedback button, so if we press the back button, it will not leave the screen and will not show the previous work.

But I do not understand what null shows here. I searched on the Internet, but I knew it was a TAG , and we could use something like this .

So my question is very simple: What does null mean here? or what does null do?

(sorry for my bad english.)

+7
android android-layout android-fragments
source share
2 answers

From the documentation , this is pretty clear:

 public abstract FragmentTransaction addToBackStack (String name) 

Add this transaction to the back stack. This means that the transaction will be remembered after it is committed and will change its action when it later pops out of the stack.

Options

 name // An optional name for this back stack state, or null. 

Thus, your parameter is optional and represents the name of the fragment.

If you just want to add this transaction to the back stack and don't need it later, you can put null as the name.

In this context, null in plain English means "I don't need a name for this snippet." That's why he says this name is optional. If you put a name, you can use that name later. If you put null , which simply means "add this snippet to the back stack and I no longer need it."

The use of a name is the identification of a particular fragment. This can be useful, for example, if you want to get this fragment from the FragmentManager :

 addToBackStack (FRAGMENT_NAME); getFragmentMangager().findFragmentByTag(FRAGMENT_NAME); 
+14
source share

I think you should not use .addToBackStack (null); if you are trying to pop up the backstack the chances are that it may throw a java.lang.IllegalStateException, as it will not have a valid Popout link for the last item added. This needs to be checked ... I'm not 100% sure.

+1
source share

All Articles