Follow treslines by email clicking Here!

Tuesday, October 8, 2013

Dynamically Fragment Replacement Android

Hi there! Today i'm gonna show how to insert(add) fragments dynamically. How to replace it thru other fragments with totally diferent layouts. This is a very common task while developing scalable, reusable and good looking apps.

I'm trying to do it in a very practical way from developer to developer. Less words and more code (complete code, and not only fragments...) to be sure you'll not run away and enjoy the sample. ;-)

There are some restrictions you must know, while handling with fragments.

First: You can only replace fragments which has been added dynamically. Burn this in your mind! ;-) I will be helpful! Believe me!
Second: You must define a "placeholder" layout, which will be your point to insert(add) and replace fragments with.

Ok lets put hands on. ;-)  The result at the end will be something like this:



Create a new Android Project with a blank template. 

Call it FragmentReplacement. Ensure that you have defined the "minsdkversion=11".

Controlling your AndroidManifest.xml 

Open it and be sure you have something similar to this:



    

    
        
            
                

                
            
        
    


Activity_main.xml (Layout) 

In the main activity layout, create a layout structure like this bellow:



    
    

    

Creating a Fragment 

In the folder "layout" create a new layout, name it "fragment_horizontal.xml" and copy/paste the code bellow in it. Save it. Done! Lets move ahead. ;-) (Don't worry about the details right now. Let's first create a simple structure before explaning everything.)



    

        


Create the next Fragment 

The main difference here is that the layout will change it here from horizontal to vertical. This because we wanna see the beautiful effect from having and using Fragments. Name it "fragment_vertical.xml" and again copy/paste the next code section in it.



    

        


Creating the class responsible for the First Fragment 

Create a new class and name it "FragmentHorizontal". While creating a new class, be sure you extend it from Fragment when using the "New Class Wizard". Or just copy the code into your new created class. That's a very simple class. It is only responsible for creating a new Fragment from the given layout we have just defined in the sections above.

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentHorizontal extends Fragment {
 
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  View view = inflater.inflate(R.layout.fragment_horizontal, null);
  Button button = (Button) view.findViewById(R.id.hbutton1);
  button.setText("horizontal");
  return view;
 }

}

Creating the next Fragment with vertical layout 

Do it analogue the section above. Create a new class and name it "FragmentVertical". Copy/Paste the code and go to the next step. ;-)

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentVertical extends Fragment {
 
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  View view = inflater.inflate(R.layout.fragment_vertical, null);
  Button button = (Button) view.findViewById(R.id.vbutton1);
  button.setText("vertical");
  return view;
 }

}

We are almost done! 

The main activity. Place the codefragment bellow into it. After that press the button in the middle to replace it as many times as you want. Press Run>Android Application

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

 private boolean flip = false;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  FragmentVertical fv = new FragmentVertical();
  FragmentManager fm = getFragmentManager();
  FragmentTransaction ft = fm.beginTransaction();
  ft.add(R.id.layoutToReplace, fv);
  ft.commit();

  Button b = (Button) findViewById(R.id.button1);
  b.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    if (!flip) {
     FragmentHorizontal fh = new FragmentHorizontal();
     FragmentManager fm = getFragmentManager();
     FragmentTransaction ft = fm.beginTransaction();
     ft.replace(R.id.layoutToReplace, fh);
     ft.commit();
     flip = true;
    } else {
     FragmentVertical fv = new FragmentVertical();
     FragmentManager fm = getFragmentManager();
     FragmentTransaction ft = fm.beginTransaction();
     ft.replace(R.id.layoutToReplace, fv);
     ft.commit();
     flip = false;
    }
   }
  });
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}
If everything went well, you should see something like that.



So that's all. I hope you like it. Have fun! ;-)

5 comments:

  1. Great article. However just for my conception shouldnt layoutToReplace actually be the container layout. I mean doesnt the fragment get added to the container rather than replacing it ?

    ReplyDelete
  2. What if we do transactions several times? We would create every time new FragmentVertical, FragmentHorizontal? Should't we reuse them if they were already created?

    ReplyDelete
  3. Very helpful, thx man!

    ReplyDelete
  4. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in android programming your post help me a lot.Thanks for your informative article. Android Training in velachery | Android Training institute in chennai

    ReplyDelete
  5. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    Android Training in chennai | Android Training

    ReplyDelete