Categories
Android

Replacing a Fragment in a Tab Layout with an ActionBar

In the post Tab Layout in Android with ActionBar and Fragment the fragments can’t be replaced later, in this post I write the changes in order to replace the first fragment of the first tab with a third fragment using a button at runtime.

  1. The project in Tab Layout in Android with ActionBar and Fragment is the starting point, and as first step you add new strings in the file /res/values/strings.xml
  2. edit the layout of the first fragment res/layout/tab1.xml to add a button that replaces the fragment
  3. create the layout of the layout for the third fragment res/layout/tab3.xml
  4. create the class of the third fragment eu\lucazanini\Tab3Fragment.java
  5. edit the main activity eu\lucazanini\TabActionBarActivity.java
  6. launch the app
    tab1_fragment3
    tab1_fragment1
    tab2_fragment2

How it works
The method onAttachFragment is overridden, called when a fragment is attached to the activity, here I add the new fragment to the variable fragList.
The most important part of the work is carried out by the method replaceFragment() of the class TabActionBarActivity, called when the user pushes the buttons because of the attribute in tab1.xml and tab3.xml android:onClick=”replaceFragment”.
The code between the lines 126 and 143 is executed when in the first fragment the button is pushed in order to open the third one.
This code can be divided into two parts:

  1. the first part between the lines 129 and 132 replaces the current fragment (the first one) with the third fragment (beginTransaction, replace and commit); note that the fragment three is added with the tag label1=”one” and not “three”, because it is inserted in the first tab and you use the tag to understand in which tab the fragment is attached
  2. the second part between the lines 134 and 141 removes the replaced fragment from the variable fragList that contains all the added fragments

A similar code is inserted into the case for the button in the third fragment.
In the method onTabSelected of the inner class TabListener mFragment is equal to f if mTag is the right one, i.e., in the case of mTag=”one” (the first tab) fragList could contain or the fragment one or the fragment three, then mFragment is equal to one of these two fragments.

Downlaod the project here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.