30

Is it possible to stick a Fragment in the layout of another Fragment? Has anyone tried this?

Blo
  • 11,903
  • 5
  • 45
  • 99
Christopher Perry
  • 38,891
  • 43
  • 145
  • 187

4 Answers4

47

Finally! the android 4.2 update comes with default support for nested fragments, also compatible: Official NestedFragments. What's more, the support of the nested Fragments in announced in the latest 11th revision of the v4 support library!

riwnodennyk
  • 8,140
  • 4
  • 35
  • 37
  • 3
    This is officially now the correct answer. Thanks for sharing, I wasn't aware of this update. – Christopher Perry Nov 29 '12 at 04:32
  • 5
    While in the fragment simply call getChildFragmentManager() instead of getFragmentManager. Solved an issue I was having right away with nested fragments using an older version of the compatability library – Zachary Moshansky Dec 05 '12 at 01:27
7

No, fragments are currently NOT in a hierarchy. Trying to have one fragment embedded in another can lead to problems, often subtle.

adarsh
  • 6,738
  • 4
  • 30
  • 52
hackbod
  • 90,665
  • 16
  • 140
  • 154
  • What sort of problems? I just successfully nested Fragments. – Christopher Perry Jun 03 '11 at 21:30
  • 1
    problems related to how the views appear on screen? or related to the life cycle of fragments? – Erdal Aug 25 '11 at 21:30
  • 1
    I assigned this as the answer, because it appears that doing this is not advisable. I did indeed have issues when doing this, even though it is "possible" to do so. – Christopher Perry Oct 04 '11 at 18:41
  • 1
    I wouldn't assign this as the answer, as its technically wrong, as you can. Just because it's not recommended doesn't mean you can't. I have it working reliably. – Chris.Jenkins Mar 14 '12 at 10:41
  • 3
    We won't promise that your app will continue to work correctly in the future. – hackbod Mar 30 '12 at 05:51
  • so if we want that fragment effect in our code then what should we do except using this compatible support package ? – Hunt Apr 09 '12 at 10:07
  • 1
    @hackbod Can you give some detail for us about fragments not being in a hierarchy, and why nesting fragments may cause problems? – Christopher Perry Oct 18 '12 at 02:23
5

Edit: As of ACLv11 this is only needed if you replace(...) ViewPagers dynamically.

Yes you can, but there are certain ways that are a pain, but I have even embedded FragmentViewPagers.

If you embed in XML then when the layout is inflated you will have no problems.

If you embed fragments dynamically within another fragment then you will get issues! Although it is possible.

Generally involves posting to a handler which then executes after the current fragment transition then starts another, this way you can embed fragments pretty easily. But this leads to other issues, so you have to be careful how you implement this.

FoodTestFeast has embedded ViewPagers which are removed and added dynamically.

My Base FragmentViewPager - Fragment that holds a view pager (Which has FragmentPagerAdapter)

I haven't seen any crashes using this yet, but let me know if anyone else does.

/**
 * @project FoodFeast
 * @author chris.jenkins
 * @created Dec 28, 2011
 */
package couk.jenxsolution.food.ui.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.viewpagerindicator.TabPageIndicator;

import couk.jenxsolution.food.R;
import couk.jenxsolution.food.app.FoodApplication;

/**
 * @author chris.jenkins
 */
public class QuizPagerBaseFragment extends QuizBaseFragment
{

    // Data
    private FragmentStatePagerAdapter mAdapter = null;

    // Views
    private int layoutRes;
    private View mRootView;
    private ViewPager mPager;
    private TabPageIndicator mIndicator;

    // Handlers
    private final Handler handler = new Handler();
    private Runnable runPager;
    private boolean mCreated = false;

    /**
     * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
     *      android.view.ViewGroup, android.os.Bundle)
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        mRootView = inflater.inflate(layoutRes, container, false);
        mPager = (ViewPager) mRootView.findViewById(R.id.pager);
        mPager.setOffscreenPageLimit(2);
        mIndicator = (TabPageIndicator) mRootView.findViewById(R.id.indicator);
        mIndicator.setTypeface(FoodApplication.getInstance().getTFs().getTypeFaceBold());

        return mRootView;
    }

    /**
     * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);
        if (runPager != null) handler.post(runPager);
        mCreated = true;
    }

    /**
     * @see android.support.v4.app.Fragment#onPause()
     */
    @Override
    public void onPause()
    {
        super.onPause();
        handler.removeCallbacks(runPager);
    }

    /**
     * Set the ViewPager adapter from this or from a subclass.
     * 
     * @author chris.jenkins
     * @param adapter
     */
    protected void setAdapter(FragmentStatePagerAdapter adapter)
    {
        mAdapter = adapter;
        // mAdapter.notifyDataSetChanged();
        runPager = new Runnable() {

            @Override
            public void run()
            {
                mPager.setAdapter(mAdapter);
                mIndicator.setViewPager(mPager);
                // mAdapter.notifyDataSetChanged();
                mIndicator.setVisibility(View.VISIBLE);
            }
        };
        if (mCreated)
        {
            handler.post(runPager);
        }
    }

    /**
     * Has to be set before onCreateView
     * 
     * @author chris.jenkins
     * @param layoutRes
     */
    protected void setLayoutRes(int layoutRes)
    {
        this.layoutRes = layoutRes;
    }

}

FYI your layout will need to look like this (or similar): NOTE THE Indicator = GONE!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.viewpagerindicator.TabPageIndicator
        android:id="@+id/indicator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:visibility="gone"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>
Chris.Jenkins
  • 13,051
  • 4
  • 60
  • 61
  • 1
    Sure I'll dig one up for you from my project. I'll update the answer. – Chris.Jenkins Mar 19 '12 at 10:01
  • @Chris.Jenkins i have one fragment in FragmentPageviewer.Fragment contain 4 values.i want to when i clicked on that value it will add or replace another fragement.is this possible? – Parag Chauhan Apr 25 '12 at 20:10
  • @parag open another question with a bit more of an exp and i'll try and answer that :) – Chris.Jenkins Apr 25 '12 at 21:01
  • @Chris.Jenkins thanks for support . finally find solution..i have take another Viewpager and create its visibility visible ,invisible . – Parag Chauhan Apr 25 '12 at 21:13
  • @Chris.Jenkins, did you see anything like that (viewpager fragment inside fragment) which works with database cursor ? I hoped to find some decent example for ViewPager with database cursor and couldn't, and also didn't find a lot of info about fragment inside another fragment - so combining both of them seems like a hard task... – Shushu Nov 04 '12 at 22:10
  • @Shushu my Moupp app uses Loaders and ViewPager inside a Fragment. Works fine. Ask a question and tweet me the link and I will answer it. I also have a gist here: https://gist.github.com/3405429 Base ViewPager fragment – Chris.Jenkins Nov 05 '12 at 14:59
  • As of ACL 11 this Hack is not needed any more. – Chris.Jenkins Nov 18 '12 at 18:44
0

A smart way to solve the impossibility to use nested fragments is to use both v4 and native fragments. It works (I use it in many apps), and in some cases is what we need to bypass this limit.

Obviously, in the activity you can use getFragmentManager() or getSupportFragmentManager() to distinguish the 2 groups of fragments.

Probably is a deprecated use of it, but it solves me many situations.

Alecs
  • 2,900
  • 1
  • 22
  • 25