Search...

Sunday, November 13, 2011

How to dynamically add the fragment in the layout in android


Step1: create your layout and inflate in your activity onCreate() method.
e.g:sample_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent" android:layout_height="match_parent">

     
                 
  <FrameLayout android:id="@+id/sample"
                  android:layout_width="fill_parent" android:layout_height="fill_parent" android:visibility="visible"/>                             
                                               
      </>

</LinearLayout>

Step2 : Create your fragment class:

e.g: SampleFragment.java

public class SampleFragment extends Fragment{

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                  Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            return inflater.inflate(R.layout.sample_test, container, false);
      }



}


Step3: Put the below code in your activity.

FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction ft=null;

ft = fragmentManager.beginTransaction();

ft.replace(R.id.sample, new SampleFragment(),"Sample_Fragment");

ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();

So in this way you can dynamically add the fragment into your activity.

2 comments:

  1. Hi, is it possible to lay down more than one fragments using this dynamic approach ?? I m bot stuck with the concepts of adding dynamic fragments.
    I m trying to create a gridview kind of layout wherein each grid would contain a fragment within inside a webview is loaded. each URL of the webview, i m getting from server and the number of such fragments would be decided by the number of url's i get from server.Badly Need help.

    ReplyDelete
  2. Sorry for the late response.

    Yes you can do it. I hope you have an activity with grid view inflated through xml layout.

    Now from your activity, you have to populate each grid item through adapter.(You have to write your own custom adapter to populate fragment).


    In your custom adapter, you can inflate your grid item layout xml(Its should have FrameLayout) which can be replaced with your desired fragment class.

    Hope this will help.

    ReplyDelete