Android: Can you nest Fragments?
Asked Answered
C

4

30

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

Chthonian answered 3/6, 2011 at 0:11 Comment(10)
have you tried it? What happened?Rowell
I haven't tried it. I'm hoping somebody else has.Chthonian
I'm with Mitch. Maybe I'm getting old but in my day people tried things to see what happened. If you've got an idea then run with it - 100% solid gold learning by experience.Shellback
I guess I'll be the guinea pig. I'll let you know the result.Chthonian
I am also trying to use a FragmentPager inside of a Fragment.Oakleil
Actually it's possible on api+17.Landloper
@Squonk: thats a way, but if the result is negative, how would a person distinguish whether it was because it was not possible, or if he did it wrongDrillmaster
@NitinBansal : If they tried it and it didn't work then at least they'd have code they could post here. It's the main point of Stack Overflow - try something first then ask for help if it fails.Shellback
Possible duplicate of Fragment Inside FragmentHeadcheese
I tried it hereHeadcheese
P
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!

Pteryla answered 14/11, 2012 at 15:28 Comment(2)
This is officially now the correct answer. Thanks for sharing, I wasn't aware of this update.Chthonian
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 libraryProstitute
K
7

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

Kilburn answered 3/6, 2011 at 2:2 Comment(7)
What sort of problems? I just successfully nested Fragments.Chthonian
problems related to how the views appear on screen? or related to the life cycle of fragments?Oakleil
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.Chthonian
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.Pure
We won't promise that your app will continue to work correctly in the future.Kilburn
so if we want that fragment effect in our code then what should we do except using this compatible support package ?Whenever
@Kilburn Can you give some detail for us about fragments not being in a hierarchy, and why nesting fragments may cause problems?Chthonian
P
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>
Pure answered 14/3, 2012 at 10:39 Comment(7)
Sure I'll dig one up for you from my project. I'll update the answer.Pure
@Pure 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?Rigatoni
@parag open another question with a bit more of an exp and i'll try and answer that :)Pure
@Pure thanks for support . finally find solution..i have take another Viewpager and create its visibility visible ,invisible .Rigatoni
@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...Murage
@Murage 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: gist.github.com/3405429 Base ViewPager fragmentPure
As of ACL 11 this Hack is not needed any more.Pure
B
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.

Belligerent answered 28/10, 2014 at 11:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.