How to add a fragment to a programmatically generated layout?












47















I have the following code working which generates fragments, but only if I am adding them to a linear layout which exists in my XML file.



LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();

Fragment myFrag= new ImageFragment();
fragTransaction.add(R.id.foodItemActvity_linearLayout_fragments, myFrag , "fragment" + fragCount);
fragTransaction.commit();


Now what if I want to add that fragment to a linear layout that does not already exist in the XML file such as



LinearLayout rowLayout = new LinearLayout();


Part 2:



    Fragment frag1 = generateAppropriateFragment(type1);
Fragment frag2 = generateAppropriateFragment(type2);

LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
LinearLayout rowLayout = new LinearLayout(this);
rowLayout.setId(12345); // add counter to end

fragmentsLayout.addView(rowLayout);
getFragmentManager().beginTransaction().add(rowLayout.getId(), frag1, "fragment_grandchild" + fragCount).commit();
fragCount++;
getFragmentManager().beginTransaction().add(rowLayout.getId(), frag2, "fragment_grandchild" + fragCount).commit();
fragCount++;









share|improve this question





























    47















    I have the following code working which generates fragments, but only if I am adding them to a linear layout which exists in my XML file.



    LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
    FragmentManager fragMan = getFragmentManager();
    FragmentTransaction fragTransaction = fragMan.beginTransaction();

    Fragment myFrag= new ImageFragment();
    fragTransaction.add(R.id.foodItemActvity_linearLayout_fragments, myFrag , "fragment" + fragCount);
    fragTransaction.commit();


    Now what if I want to add that fragment to a linear layout that does not already exist in the XML file such as



    LinearLayout rowLayout = new LinearLayout();


    Part 2:



        Fragment frag1 = generateAppropriateFragment(type1);
    Fragment frag2 = generateAppropriateFragment(type2);

    LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
    LinearLayout rowLayout = new LinearLayout(this);
    rowLayout.setId(12345); // add counter to end

    fragmentsLayout.addView(rowLayout);
    getFragmentManager().beginTransaction().add(rowLayout.getId(), frag1, "fragment_grandchild" + fragCount).commit();
    fragCount++;
    getFragmentManager().beginTransaction().add(rowLayout.getId(), frag2, "fragment_grandchild" + fragCount).commit();
    fragCount++;









    share|improve this question



























      47












      47








      47


      23






      I have the following code working which generates fragments, but only if I am adding them to a linear layout which exists in my XML file.



      LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
      FragmentManager fragMan = getFragmentManager();
      FragmentTransaction fragTransaction = fragMan.beginTransaction();

      Fragment myFrag= new ImageFragment();
      fragTransaction.add(R.id.foodItemActvity_linearLayout_fragments, myFrag , "fragment" + fragCount);
      fragTransaction.commit();


      Now what if I want to add that fragment to a linear layout that does not already exist in the XML file such as



      LinearLayout rowLayout = new LinearLayout();


      Part 2:



          Fragment frag1 = generateAppropriateFragment(type1);
      Fragment frag2 = generateAppropriateFragment(type2);

      LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
      LinearLayout rowLayout = new LinearLayout(this);
      rowLayout.setId(12345); // add counter to end

      fragmentsLayout.addView(rowLayout);
      getFragmentManager().beginTransaction().add(rowLayout.getId(), frag1, "fragment_grandchild" + fragCount).commit();
      fragCount++;
      getFragmentManager().beginTransaction().add(rowLayout.getId(), frag2, "fragment_grandchild" + fragCount).commit();
      fragCount++;









      share|improve this question
















      I have the following code working which generates fragments, but only if I am adding them to a linear layout which exists in my XML file.



      LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
      FragmentManager fragMan = getFragmentManager();
      FragmentTransaction fragTransaction = fragMan.beginTransaction();

      Fragment myFrag= new ImageFragment();
      fragTransaction.add(R.id.foodItemActvity_linearLayout_fragments, myFrag , "fragment" + fragCount);
      fragTransaction.commit();


      Now what if I want to add that fragment to a linear layout that does not already exist in the XML file such as



      LinearLayout rowLayout = new LinearLayout();


      Part 2:



          Fragment frag1 = generateAppropriateFragment(type1);
      Fragment frag2 = generateAppropriateFragment(type2);

      LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
      LinearLayout rowLayout = new LinearLayout(this);
      rowLayout.setId(12345); // add counter to end

      fragmentsLayout.addView(rowLayout);
      getFragmentManager().beginTransaction().add(rowLayout.getId(), frag1, "fragment_grandchild" + fragCount).commit();
      fragCount++;
      getFragmentManager().beginTransaction().add(rowLayout.getId(), frag2, "fragment_grandchild" + fragCount).commit();
      fragCount++;






      android android-fragments android-linearlayout






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 12 '17 at 11:22









      jpihl

      3,89822337




      3,89822337










      asked Aug 18 '13 at 7:48









      ZapnologicaZapnologica

      8,96933101189




      8,96933101189
























          3 Answers
          3






          active

          oldest

          votes


















          92














          At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml.
          This is just a suggestion of mine and probably one of many solutions, but it works:
          Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.



          It could look like this:



          LinearLayout rowLayout = new LinearLayout();
          rowLayout.setId(whateveryouwantasid);
          // add rowLayout to the root layout somewhere here

          FragmentManager fragMan = getFragmentManager();
          FragmentTransaction fragTransaction = fragMan.beginTransaction();

          Fragment myFrag = new ImageFragment();
          fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
          fragTransaction.commit();


          Simply choose whatever Integer value you want for the ID:



          rowLayout.setId(12345);


          If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.



          UPDATE:



          Here is the full code of how it should be done:
          (this code is tested and works)
          I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".



          MainActivity.java:



          public class MainActivity extends Activity {

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

          LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

          LinearLayout ll = new LinearLayout(this);
          ll.setOrientation(LinearLayout.HORIZONTAL);

          ll.setId(12345);

          getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
          getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

          fragContainer.addView(ll);
          }
          }


          TestFragment.java:



          public class TestFragment extends Fragment {

          public static TestFragment newInstance(String text) {

          TestFragment f = new TestFragment();

          Bundle b = new Bundle();
          b.putString("text", text);
          f.setArguments(b);
          return f;
          }

          @Override
          public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

          View v = inflater.inflate(R.layout.fragment, container, false);

          ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));
          return v;
          }
          }


          activity_main.xml:



          <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/rlMain"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:padding="5dp"
          tools:context=".MainActivity" >

          <TextView
          android:id="@+id/textView1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/hello_world" />

          <LinearLayout
          android:id="@+id/llFragmentContainer"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_alignLeft="@+id/textView1"
          android:layout_below="@+id/textView1"
          android:layout_marginTop="19dp"
          android:orientation="vertical" >
          </LinearLayout>
          </RelativeLayout>


          fragment.xml:



            <?xml version="1.0" encoding="utf-8"?>
          <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="200dp"
          android:layout_height="200dp" >

          <TextView
          android:id="@+id/tvFragText"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_centerHorizontal="true"
          android:layout_centerVertical="true"
          android:text="" />

          </RelativeLayout>


          And this is the result of the above code: (the two Fragments are aligned next to each other)
          result






          share|improve this answer


























          • That is exactly what I am trying to do!! Only thing is what must I set the id as? Cause it wants an INT and normally in the xml files the id is a string ?

            – Zapnologica
            Aug 18 '13 at 8:13











          • This will absolutely work. @Zapnologica Look on SO to find how to generate unique ids. But, it shouldn't be a problem to use something like 647589.

            – Vikram
            Aug 18 '13 at 8:20











          • Just choose whatever Integer you want as the id :)

            – Philipp Jahoda
            Aug 18 '13 at 8:24






          • 3





            stackoverflow.com/questions/8460680/… >> Good Link

            – Zapnologica
            Aug 18 '13 at 8:31






          • 7





            I'd recommend using View.generateViewId() to generate a view ID.

            – Jeremy Wiebe
            Aug 30 '16 at 19:54



















          0














          Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear).
          You can change number 3 with any other number or take a number from a spinner!



          for (int i = 0; i < 3; i++) {
          LinearLayout linearDummy = new LinearLayout(getActivity());
          linearDummy.setOrientation(LinearLayout.VERTICAL);
          if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

          Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

          } else {
          linearDummy.setId(View.generateViewId());
          }
          fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

          xNumberLinear.addView(linearDummy);
          }





          share|improve this answer































            0















            Add this code in your activity




            FragmentTransaction mFragmentTransaction=getSupportFragmentManager().beginTransaction();
            mFragmentTransaction.add(R.id.fr_container,new ProductListFragment());
            mFragmentTransaction.commit();






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18296868%2fhow-to-add-a-fragment-to-a-programmatically-generated-layout%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              92














              At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml.
              This is just a suggestion of mine and probably one of many solutions, but it works:
              Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.



              It could look like this:



              LinearLayout rowLayout = new LinearLayout();
              rowLayout.setId(whateveryouwantasid);
              // add rowLayout to the root layout somewhere here

              FragmentManager fragMan = getFragmentManager();
              FragmentTransaction fragTransaction = fragMan.beginTransaction();

              Fragment myFrag = new ImageFragment();
              fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
              fragTransaction.commit();


              Simply choose whatever Integer value you want for the ID:



              rowLayout.setId(12345);


              If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.



              UPDATE:



              Here is the full code of how it should be done:
              (this code is tested and works)
              I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".



              MainActivity.java:



              public class MainActivity extends Activity {

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

              LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

              LinearLayout ll = new LinearLayout(this);
              ll.setOrientation(LinearLayout.HORIZONTAL);

              ll.setId(12345);

              getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
              getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

              fragContainer.addView(ll);
              }
              }


              TestFragment.java:



              public class TestFragment extends Fragment {

              public static TestFragment newInstance(String text) {

              TestFragment f = new TestFragment();

              Bundle b = new Bundle();
              b.putString("text", text);
              f.setArguments(b);
              return f;
              }

              @Override
              public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

              View v = inflater.inflate(R.layout.fragment, container, false);

              ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));
              return v;
              }
              }


              activity_main.xml:



              <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/rlMain"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:padding="5dp"
              tools:context=".MainActivity" >

              <TextView
              android:id="@+id/textView1"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/hello_world" />

              <LinearLayout
              android:id="@+id/llFragmentContainer"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_alignLeft="@+id/textView1"
              android:layout_below="@+id/textView1"
              android:layout_marginTop="19dp"
              android:orientation="vertical" >
              </LinearLayout>
              </RelativeLayout>


              fragment.xml:



                <?xml version="1.0" encoding="utf-8"?>
              <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="200dp"
              android:layout_height="200dp" >

              <TextView
              android:id="@+id/tvFragText"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerHorizontal="true"
              android:layout_centerVertical="true"
              android:text="" />

              </RelativeLayout>


              And this is the result of the above code: (the two Fragments are aligned next to each other)
              result






              share|improve this answer


























              • That is exactly what I am trying to do!! Only thing is what must I set the id as? Cause it wants an INT and normally in the xml files the id is a string ?

                – Zapnologica
                Aug 18 '13 at 8:13











              • This will absolutely work. @Zapnologica Look on SO to find how to generate unique ids. But, it shouldn't be a problem to use something like 647589.

                – Vikram
                Aug 18 '13 at 8:20











              • Just choose whatever Integer you want as the id :)

                – Philipp Jahoda
                Aug 18 '13 at 8:24






              • 3





                stackoverflow.com/questions/8460680/… >> Good Link

                – Zapnologica
                Aug 18 '13 at 8:31






              • 7





                I'd recommend using View.generateViewId() to generate a view ID.

                – Jeremy Wiebe
                Aug 30 '16 at 19:54
















              92














              At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml.
              This is just a suggestion of mine and probably one of many solutions, but it works:
              Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.



              It could look like this:



              LinearLayout rowLayout = new LinearLayout();
              rowLayout.setId(whateveryouwantasid);
              // add rowLayout to the root layout somewhere here

              FragmentManager fragMan = getFragmentManager();
              FragmentTransaction fragTransaction = fragMan.beginTransaction();

              Fragment myFrag = new ImageFragment();
              fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
              fragTransaction.commit();


              Simply choose whatever Integer value you want for the ID:



              rowLayout.setId(12345);


              If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.



              UPDATE:



              Here is the full code of how it should be done:
              (this code is tested and works)
              I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".



              MainActivity.java:



              public class MainActivity extends Activity {

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

              LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

              LinearLayout ll = new LinearLayout(this);
              ll.setOrientation(LinearLayout.HORIZONTAL);

              ll.setId(12345);

              getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
              getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

              fragContainer.addView(ll);
              }
              }


              TestFragment.java:



              public class TestFragment extends Fragment {

              public static TestFragment newInstance(String text) {

              TestFragment f = new TestFragment();

              Bundle b = new Bundle();
              b.putString("text", text);
              f.setArguments(b);
              return f;
              }

              @Override
              public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

              View v = inflater.inflate(R.layout.fragment, container, false);

              ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));
              return v;
              }
              }


              activity_main.xml:



              <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/rlMain"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:padding="5dp"
              tools:context=".MainActivity" >

              <TextView
              android:id="@+id/textView1"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/hello_world" />

              <LinearLayout
              android:id="@+id/llFragmentContainer"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_alignLeft="@+id/textView1"
              android:layout_below="@+id/textView1"
              android:layout_marginTop="19dp"
              android:orientation="vertical" >
              </LinearLayout>
              </RelativeLayout>


              fragment.xml:



                <?xml version="1.0" encoding="utf-8"?>
              <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="200dp"
              android:layout_height="200dp" >

              <TextView
              android:id="@+id/tvFragText"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerHorizontal="true"
              android:layout_centerVertical="true"
              android:text="" />

              </RelativeLayout>


              And this is the result of the above code: (the two Fragments are aligned next to each other)
              result






              share|improve this answer


























              • That is exactly what I am trying to do!! Only thing is what must I set the id as? Cause it wants an INT and normally in the xml files the id is a string ?

                – Zapnologica
                Aug 18 '13 at 8:13











              • This will absolutely work. @Zapnologica Look on SO to find how to generate unique ids. But, it shouldn't be a problem to use something like 647589.

                – Vikram
                Aug 18 '13 at 8:20











              • Just choose whatever Integer you want as the id :)

                – Philipp Jahoda
                Aug 18 '13 at 8:24






              • 3





                stackoverflow.com/questions/8460680/… >> Good Link

                – Zapnologica
                Aug 18 '13 at 8:31






              • 7





                I'd recommend using View.generateViewId() to generate a view ID.

                – Jeremy Wiebe
                Aug 30 '16 at 19:54














              92












              92








              92







              At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml.
              This is just a suggestion of mine and probably one of many solutions, but it works:
              Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.



              It could look like this:



              LinearLayout rowLayout = new LinearLayout();
              rowLayout.setId(whateveryouwantasid);
              // add rowLayout to the root layout somewhere here

              FragmentManager fragMan = getFragmentManager();
              FragmentTransaction fragTransaction = fragMan.beginTransaction();

              Fragment myFrag = new ImageFragment();
              fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
              fragTransaction.commit();


              Simply choose whatever Integer value you want for the ID:



              rowLayout.setId(12345);


              If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.



              UPDATE:



              Here is the full code of how it should be done:
              (this code is tested and works)
              I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".



              MainActivity.java:



              public class MainActivity extends Activity {

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

              LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

              LinearLayout ll = new LinearLayout(this);
              ll.setOrientation(LinearLayout.HORIZONTAL);

              ll.setId(12345);

              getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
              getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

              fragContainer.addView(ll);
              }
              }


              TestFragment.java:



              public class TestFragment extends Fragment {

              public static TestFragment newInstance(String text) {

              TestFragment f = new TestFragment();

              Bundle b = new Bundle();
              b.putString("text", text);
              f.setArguments(b);
              return f;
              }

              @Override
              public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

              View v = inflater.inflate(R.layout.fragment, container, false);

              ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));
              return v;
              }
              }


              activity_main.xml:



              <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/rlMain"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:padding="5dp"
              tools:context=".MainActivity" >

              <TextView
              android:id="@+id/textView1"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/hello_world" />

              <LinearLayout
              android:id="@+id/llFragmentContainer"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_alignLeft="@+id/textView1"
              android:layout_below="@+id/textView1"
              android:layout_marginTop="19dp"
              android:orientation="vertical" >
              </LinearLayout>
              </RelativeLayout>


              fragment.xml:



                <?xml version="1.0" encoding="utf-8"?>
              <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="200dp"
              android:layout_height="200dp" >

              <TextView
              android:id="@+id/tvFragText"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerHorizontal="true"
              android:layout_centerVertical="true"
              android:text="" />

              </RelativeLayout>


              And this is the result of the above code: (the two Fragments are aligned next to each other)
              result






              share|improve this answer















              At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml.
              This is just a suggestion of mine and probably one of many solutions, but it works:
              Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.



              It could look like this:



              LinearLayout rowLayout = new LinearLayout();
              rowLayout.setId(whateveryouwantasid);
              // add rowLayout to the root layout somewhere here

              FragmentManager fragMan = getFragmentManager();
              FragmentTransaction fragTransaction = fragMan.beginTransaction();

              Fragment myFrag = new ImageFragment();
              fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
              fragTransaction.commit();


              Simply choose whatever Integer value you want for the ID:



              rowLayout.setId(12345);


              If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.



              UPDATE:



              Here is the full code of how it should be done:
              (this code is tested and works)
              I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".



              MainActivity.java:



              public class MainActivity extends Activity {

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

              LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

              LinearLayout ll = new LinearLayout(this);
              ll.setOrientation(LinearLayout.HORIZONTAL);

              ll.setId(12345);

              getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
              getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

              fragContainer.addView(ll);
              }
              }


              TestFragment.java:



              public class TestFragment extends Fragment {

              public static TestFragment newInstance(String text) {

              TestFragment f = new TestFragment();

              Bundle b = new Bundle();
              b.putString("text", text);
              f.setArguments(b);
              return f;
              }

              @Override
              public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

              View v = inflater.inflate(R.layout.fragment, container, false);

              ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));
              return v;
              }
              }


              activity_main.xml:



              <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/rlMain"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:padding="5dp"
              tools:context=".MainActivity" >

              <TextView
              android:id="@+id/textView1"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/hello_world" />

              <LinearLayout
              android:id="@+id/llFragmentContainer"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_alignLeft="@+id/textView1"
              android:layout_below="@+id/textView1"
              android:layout_marginTop="19dp"
              android:orientation="vertical" >
              </LinearLayout>
              </RelativeLayout>


              fragment.xml:



                <?xml version="1.0" encoding="utf-8"?>
              <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="200dp"
              android:layout_height="200dp" >

              <TextView
              android:id="@+id/tvFragText"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerHorizontal="true"
              android:layout_centerVertical="true"
              android:text="" />

              </RelativeLayout>


              And this is the result of the above code: (the two Fragments are aligned next to each other)
              result







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Feb 11 '17 at 20:44









              Willi Mentzel

              9,277114470




              9,277114470










              answered Aug 18 '13 at 7:59









              Philipp JahodaPhilipp Jahoda

              37k17121145




              37k17121145













              • That is exactly what I am trying to do!! Only thing is what must I set the id as? Cause it wants an INT and normally in the xml files the id is a string ?

                – Zapnologica
                Aug 18 '13 at 8:13











              • This will absolutely work. @Zapnologica Look on SO to find how to generate unique ids. But, it shouldn't be a problem to use something like 647589.

                – Vikram
                Aug 18 '13 at 8:20











              • Just choose whatever Integer you want as the id :)

                – Philipp Jahoda
                Aug 18 '13 at 8:24






              • 3





                stackoverflow.com/questions/8460680/… >> Good Link

                – Zapnologica
                Aug 18 '13 at 8:31






              • 7





                I'd recommend using View.generateViewId() to generate a view ID.

                – Jeremy Wiebe
                Aug 30 '16 at 19:54



















              • That is exactly what I am trying to do!! Only thing is what must I set the id as? Cause it wants an INT and normally in the xml files the id is a string ?

                – Zapnologica
                Aug 18 '13 at 8:13











              • This will absolutely work. @Zapnologica Look on SO to find how to generate unique ids. But, it shouldn't be a problem to use something like 647589.

                – Vikram
                Aug 18 '13 at 8:20











              • Just choose whatever Integer you want as the id :)

                – Philipp Jahoda
                Aug 18 '13 at 8:24






              • 3





                stackoverflow.com/questions/8460680/… >> Good Link

                – Zapnologica
                Aug 18 '13 at 8:31






              • 7





                I'd recommend using View.generateViewId() to generate a view ID.

                – Jeremy Wiebe
                Aug 30 '16 at 19:54

















              That is exactly what I am trying to do!! Only thing is what must I set the id as? Cause it wants an INT and normally in the xml files the id is a string ?

              – Zapnologica
              Aug 18 '13 at 8:13





              That is exactly what I am trying to do!! Only thing is what must I set the id as? Cause it wants an INT and normally in the xml files the id is a string ?

              – Zapnologica
              Aug 18 '13 at 8:13













              This will absolutely work. @Zapnologica Look on SO to find how to generate unique ids. But, it shouldn't be a problem to use something like 647589.

              – Vikram
              Aug 18 '13 at 8:20





              This will absolutely work. @Zapnologica Look on SO to find how to generate unique ids. But, it shouldn't be a problem to use something like 647589.

              – Vikram
              Aug 18 '13 at 8:20













              Just choose whatever Integer you want as the id :)

              – Philipp Jahoda
              Aug 18 '13 at 8:24





              Just choose whatever Integer you want as the id :)

              – Philipp Jahoda
              Aug 18 '13 at 8:24




              3




              3





              stackoverflow.com/questions/8460680/… >> Good Link

              – Zapnologica
              Aug 18 '13 at 8:31





              stackoverflow.com/questions/8460680/… >> Good Link

              – Zapnologica
              Aug 18 '13 at 8:31




              7




              7





              I'd recommend using View.generateViewId() to generate a view ID.

              – Jeremy Wiebe
              Aug 30 '16 at 19:54





              I'd recommend using View.generateViewId() to generate a view ID.

              – Jeremy Wiebe
              Aug 30 '16 at 19:54













              0














              Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear).
              You can change number 3 with any other number or take a number from a spinner!



              for (int i = 0; i < 3; i++) {
              LinearLayout linearDummy = new LinearLayout(getActivity());
              linearDummy.setOrientation(LinearLayout.VERTICAL);
              if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

              Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

              } else {
              linearDummy.setId(View.generateViewId());
              }
              fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

              xNumberLinear.addView(linearDummy);
              }





              share|improve this answer




























                0














                Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear).
                You can change number 3 with any other number or take a number from a spinner!



                for (int i = 0; i < 3; i++) {
                LinearLayout linearDummy = new LinearLayout(getActivity());
                linearDummy.setOrientation(LinearLayout.VERTICAL);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

                } else {
                linearDummy.setId(View.generateViewId());
                }
                fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

                xNumberLinear.addView(linearDummy);
                }





                share|improve this answer


























                  0












                  0








                  0







                  Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear).
                  You can change number 3 with any other number or take a number from a spinner!



                  for (int i = 0; i < 3; i++) {
                  LinearLayout linearDummy = new LinearLayout(getActivity());
                  linearDummy.setOrientation(LinearLayout.VERTICAL);
                  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                  Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

                  } else {
                  linearDummy.setId(View.generateViewId());
                  }
                  fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

                  xNumberLinear.addView(linearDummy);
                  }





                  share|improve this answer













                  Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear).
                  You can change number 3 with any other number or take a number from a spinner!



                  for (int i = 0; i < 3; i++) {
                  LinearLayout linearDummy = new LinearLayout(getActivity());
                  linearDummy.setOrientation(LinearLayout.VERTICAL);
                  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                  Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

                  } else {
                  linearDummy.setId(View.generateViewId());
                  }
                  fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

                  xNumberLinear.addView(linearDummy);
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 21 '18 at 14:57









                  FarmakerFarmaker

                  9114




                  9114























                      0















                      Add this code in your activity




                      FragmentTransaction mFragmentTransaction=getSupportFragmentManager().beginTransaction();
                      mFragmentTransaction.add(R.id.fr_container,new ProductListFragment());
                      mFragmentTransaction.commit();






                      share|improve this answer




























                        0















                        Add this code in your activity




                        FragmentTransaction mFragmentTransaction=getSupportFragmentManager().beginTransaction();
                        mFragmentTransaction.add(R.id.fr_container,new ProductListFragment());
                        mFragmentTransaction.commit();






                        share|improve this answer


























                          0












                          0








                          0








                          Add this code in your activity




                          FragmentTransaction mFragmentTransaction=getSupportFragmentManager().beginTransaction();
                          mFragmentTransaction.add(R.id.fr_container,new ProductListFragment());
                          mFragmentTransaction.commit();






                          share|improve this answer














                          Add this code in your activity




                          FragmentTransaction mFragmentTransaction=getSupportFragmentManager().beginTransaction();
                          mFragmentTransaction.add(R.id.fr_container,new ProductListFragment());
                          mFragmentTransaction.commit();







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 21 '18 at 7:42









                          bhoomikabhoomika

                          42758




                          42758






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18296868%2fhow-to-add-a-fragment-to-a-programmatically-generated-layout%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                              Alcedinidae

                              RAC Tourist Trophy