Tutorial details

Android Fragment transaction: FragmentManager and Backstack | App Code for Sale | Preview

Android Fragment transaction: FragmentManager and Backstack | Android Tutorial

How to create fragment

Overview PAGE TOP

Fragments are useful when we want to support multiple screen size. To manage fragments we need a FragmentManager that help us to handle trasaction between fragments. With transaction we mean a sequence of steps to add, replace or remove fragments. In the last post we showed how to support multiple screen size and orientation using fragments. Now we want to go a bit further.

In Android there are two different methods to create fragment:

  • static method
  • dynamic method

Static method is when we “write” directly our fragment in XML file. This is an example:

01  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
02      xmlns:tools="http://schemas.android.com/tools"
03      android:layout_width="match_parent"
04      android:layout_height="match_parent"
05      android:paddingBottom="@dimen/activity_vertical_margin"
06      android:paddingLeft="@dimen/activity_horizontal_margin"
07      android:paddingRight="@dimen/activity_horizontal_margin"
08      android:paddingTop="@dimen/activity_vertical_margin"
09      tools:context=".MainActivity"
10      android:orientation="horizontal" >
12          <fragment android:id="@+id/listFragment"
13                android:layout_width="0dp"
14                android:layout_height="wrap_content"
15                class="com.survivingwithandroid.fragment.LinkListFragment"
16                android:layout_weight="2"/>
17  </LinearLayout>

In this case our layout isn’t dynamic because we can’t manage the fragment at runtime. So if we want to make our layout dynamic (and this happen very often) we need to do it in another way. We have to use FrameLayout. With FrameLayout we can handle fragments as we need at runtime, but to do it we need a manager, in other words a component that can handle fragments. This is FragmentManager. This component can add, replace and remove fragments at runtime. The layout above becomes:

01  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
02      xmlns:tools="http://schemas.android.com/tools"
03      android:layout_width="match_parent"
04      android:layout_height="match_parent"
05      android:paddingBottom="@dimen/activity_vertical_margin"
06      android:paddingLeft="@dimen/activity_horizontal_margin"
07      android:paddingRight="@dimen/activity_horizontal_margin"
08      android:paddingTop="@dimen/activity_vertical_margin"
09      tools:context=".MainActivity" >
11      <FrameLayout
12          android:id="@+id/listFragment"
13          android:layout_width="wrap_content"
14          android:layout_height="wrap_content"
15      />
17  </RelativeLayout>

So now we have all the freedom to “inject” in the FrameLayout our fragments.


As we said before FragmentManager is the key component. Using FragmentManager we can discover ( find) fragment inside our layout using findFragmentById or findFragmentByTag. While the first method is very simple and we use the common android id to discover the component, the second method (that uses tag) is unsual. A tag in a fragment is simply a “name” we give to the fragment so that we can find it later using that name. We are more interested in some other methods.

All the operation that are made by the FragmentManager happens inside a “transaction” like in a database operation. First, we can get the FragmentManger using the Activity method getFragmentManager(). Once we have the reference to this component we have to start the transaction in this way:

1   FragmentManager fm = getFragmentManager();
3   // Transaction start
4   FragmentTransaction ft = fm.beginTransaction();
6   .......
8   // Transaction commint
9   ft.commit();

At the end when we finished and we are ready to show our fragment we have to call the commit method that marks the end of the transaction. For example, if we remember the example we showed in the last post, and using a FrameLayout we can “insert” the link list in this way:

01  public class MainActivity extends Activity implements ChangeLinkListener{
03      @Override
04      protected void onCreate(Bundle savedInstanceState) {
05          super.onCreate(savedInstanceState);
06          setContentView(R.layout.activity_main);
08          FragmentManager fm = getFragmentManager();
09          FragmentTransaction ft = fm.beginTransaction();
11          LinkListFragment llf = new LinkListFragment();
12          ft.replace(R.id.listFragment, llf);
13          ft.commit();
14      }
15    ...
17  }

But…What kind of operation we can perform inside the transaction?…Well we can:

  • add a new fragment
  • replace an existing fragment
  • remove a fragment

If we remember the example we used last time every time an user clicks on a link the interface method onLinkChange is called. So in this method we want to show how to perform the operation listed above.

01  if (findViewById(R.id.fragPage) != null) {
02      WebViewFragment wvf = (WebViewFragment) getFragmentManager().findFragmentById(R.id.fragPage);
04  // Part 1: Tablet and so on
05      if (wvf == null) {
06          System.out.println("Dual fragment - 1");
07          wvf = new WebViewFragment();
08          wvf.init(linkData.getLink());
09          // We are in dual fragment (Tablet and so on)
10          FragmentManager fm = getFragmentManager();
11          FragmentTransaction ft = fm.beginTransaction();
12          //wvf.updateUrl(link);
13          ft.add(R.id.fragPage, wvf);
14          ft.commit();
16      }
17      else {
18       Log.d("SwA", "Dual Fragment update");
19       wvf = new WebViewFragment();
20        wvf.init(linkData.getLink());
21        FragmentManager fm = getFragmentManager();
22       FragmentTransaction ft = fm.beginTransaction();           
23       ft.replace(R.id.fragPage, wvf);
24       ft.commit();
26       //wvf.updateUrl(linkData.getLink());
27      }
28  }
29  else {
30      Log.d("SwA", "replace");
31      FragmentTransaction ft = getFragmentManager().beginTransaction();
32      WebViewFragment wvf =  new WebViewFragment();
33      wvf.init(linkData.getLink());
34      ft.replace(R.id.listFragment, wvf);
35      ft.commit();
36  }

If you compare this piece of code with the last example in the previous post you notice some differences. First in the green part we don’t start an activity anymore when user clicks on a link but we simply replace the FrameLayout with a fragment showing the web page. More over, in the yellow part we don’t update the current fragment inside the FrameLayout but we create a new fragment and we replace the existing fragment with the one just created. The app behaviour is always the same but we obtained this behaviour in a different way, using dynamic fragments inside our layout.

If you run the app and start using it you can notice a “wired” behaviour when you press back button. We’d expect that the back button would bring us to the last web page visited but it isn’t like we supposed. When you press back button you come to the home page.



Fragment Backstack

Well the behaviour described above is normal because the back button acts at activity level not at the fragment level. So our activity is the same while we replace fragments as the user interacts with the app. In this way when we tap on the back button we select the first activity on the activity stack, in our case the home. We don’t want this behaviour but we want that when we click on the back button we go back in the fragments stack. We can achieve it adding the fragment to the backstack. We do it in this way:

01  @Override
02  public void onLinkChange(LinkData linkData) {       
03      System.out.println("Listener");
04      // Here we detect if there's dual fragment
05      if (findViewById(R.id.fragPage) != null) {
06          WebViewFragment wvf = (WebViewFragment) getFragmentManager().findFragmentById(R.id.fragPage);
08          if (wvf == null) {
09              System.out.println("Dual fragment - 1");
10              wvf = new WebViewFragment();
11              wvf.init(linkData.getLink());
12              // We are in dual fragment (Tablet and so on)
13              FragmentManager fm = getFragmentManager();
14              FragmentTransaction ft = fm.beginTransaction();
15              //wvf.updateUrl(link);
16              ft.add(R.id.fragPage, wvf);
17              ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
18              // Add to backstack
19              ft.addToBackStack(linkData.getName());
20              ft.commit();
22          }
23          else {
24           Log.d("SwA", "Dual Fragment update");
25           wvf = new WebViewFragment();
26            wvf.init(linkData.getLink());
27            FragmentManager fm = getFragmentManager();
28           FragmentTransaction ft = fm.beginTransaction();           
29           ft.replace(R.id.fragPage, wvf);
30           ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
31            // Add to backstack
32            ft.addToBackStack(linkData.getName());
33            ft.commit();
35           //wvf.updateUrl(linkData.getLink());
36          }
37      }
38      else {
39          /*
40          System.out.println("Start Activity");
41          Intent i = new Intent(this, WebViewActivity.class);
42          i.putExtra("link", link);
43          startActivity(i);
44          */
45             Log.d("SwA", "replace");
46          FragmentTransaction ft = getFragmentManager().beginTransaction();
47          WebViewFragment wvf =  new WebViewFragment();
48          wvf.init(linkData.getLink());
50          ft.addToBackStack(linkData.getName());
51          ft.replace(R.id.listFragment, wvf);
52          ft.commit();
53      }
55  }

We use the addToBackStack method of the FragmentTrasaction and we add every fragment to the backstack. In this way when we tap on the back button we have the correct behaviour.

Reference PAGE TOP


0 Comments Leave a comment

Please login in order to leave a comment.

Newest first

to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.