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! ;-)

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†