How to set a ViewPager inside a Fragment
C

7

56

I need to place a ViewPager inside of a fragment, but I have two fragments, Fragment 1 is my MENU, and Fragment 2 I want to use as a ViewPagerIndicator.

But a fragment can't have another fragment... what do I need to do for that?

enter image description here

Christine answered 29/9, 2013 at 1:35 Comment(0)
H
106

Starting in Android 4.2, there are nested fragments.http://developer.android.com/about/versions/android-4.2.html#NestedFragments The support library now also includes support for this for older Android versions.

So you can do something like this:

@Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
    mViewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
    }

Full implementation available here: https://github.com/marcoRS/nested-fragments/tree/master/src/com/burnside/digital/nestedfragments

House answered 29/9, 2013 at 1:54 Comment(7)
But is not possible because i cant put a FragmentActivity inside of my Fragment 2 , because the fragment parent is a FragmentActivity, and the child(fragment 2) needs to be a fragmentActivity to have the tabs.. and in the github example dont put a fragment inside an other fragment.Christine
Why do you even need to have fragment 1? Can't you just have a viewpager that references different fragments and then have Fragment 2 below it?House
but the fragment 1 is always the same and this would look like changes, and do not want that.. some idea?Christine
yeah Simply use getChildFragmetManager() Instead of getFragmentManager() or getSupportFragmentManger(),when you initiating adapter. And it will definitely works :) ,Happy Coding.Weitzman
It Worked. I was using getSupportFragmentManager() instead of getChildFragmentManager() when initializing the ViewPagerAdapter inside fragment .Ridotto
Full Implementation Link Dead.....................................Heliostat
The example is no longer functional!Talos
S
38

You must use getChildFragmentManager() instead of getSupportFragmentManager() to get the FragmentManger inside a Fragment. But you should not use FragmentStatePagerAdapter rather than FragmentPagerAdapter.

Syphilology answered 21/12, 2015 at 16:9 Comment(2)
"Not use FragmentStatePagerAdapter rather than FragmentPagerAdapter".. Unraveling the triple negative, you mean we SHOULD USE FragmentPagerAdapter, right? And why is that?Soar
"But you should not use FragmentStatePagerAdapter rather than FragmentPagerAdapter." Once again FragmentPagerAdapter saved my day. This happening to me second time but i didnt realize until saw this. Reason: if you try to use FragmentStatePagerAdapter in a viewPager that in a fragment your option menu could be messed up(or doesn't show up at all) if you navigate to another page and came backLissner
P
18

Just use getChildFragmentManager() instead of getSupportFragmentManager() inside Fragments.

Inside Fragments

new ViewPagerAdapter(getChildFragmentManager());

Inside Activity

new ViewPagerAdapter(getSupportFragmentManager());

Simple Code

fragment_sample.xml layout

<?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.google.android.material.tabs.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

SampleFragment.java class

public class SampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View fragmentView = inflater.inflate(R.layout.fragment_sample, container, false);
        return fragmentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // find views by id
        ViewPager viewPager = view.findViewById(R.id.viewpager);
        TabLayout tabLayout = view.findViewById(R.id.tablayout);

        // attach tablayout with viewpager
        tabLayout.setupWithViewPager(viewPager);

        ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());

        // add your fragments
        adapter.addFrag(new SampleFragment(), "Tab1");
        adapter.addFrag(new SampleFragment2(), "Tab2");
        adapter.addFrag(new SampleFragment3(), "Tab3");

        // set adapter on viewpager
        viewPager.setAdapter(adapter);
    }
}

ViewPagerAdapter.java class

// common adapter for all view pager in your project.
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

    public void addFrag(Fragment fragment) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add("");
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }
}

Important Related Links

Pustulant answered 16/11, 2018 at 7:25 Comment(1)
SampleFragment() in the line adapter.addFrag(new SampleFragment(), "Tab1"); should be changed to SampleFragment1(), since SampleFragment() is already defined as the fragment holding the ViewPager @KhemrajGape
P
4

it is possible. try to do this code view_pager_fragment.xml file

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

ViewPagerFragment

ViewPager viewPager;
TabLayout tabLayout;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tracks, container, false);

    viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    tabLayout = (TabLayout) view.findViewById(R.id.tab);

    return view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    setupViewPager(viewPager);
    tabLayout.setupWithViewPager(viewPager);

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());``

  

    viewPager.setAdapter(viewPagerAdapter);
}

private class ViewPagerAdapter extends FragmentPagerAdapter {

    public ViewPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Fragment getItem(int position) {
        if(position == 0) return new FirstFragment();
        if(position == 1) return new SecoundFragment();
        if(position == 2) return new LoginFragment();
        throw new IllegalStateException("Position is unexpectedly " + position);
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if(position == 0) return "First";
        if(position == 1) return "Secound";
        if(position == 2) return "Login";
        throw new IllegalStateException("Position is unexpectedly " + position);
    }
}
Profuse answered 30/5, 2017 at 10:26 Comment(0)
V
0

With the Android Support V4 library, you can add a fragment inside another fragment. Try to use it, it may can resolve your problem.

Voss answered 29/9, 2013 at 1:52 Comment(2)
But is not possible because i cant put a FragmentActivity inside of my Fragment 2 , because the fragment parent is a FragmentActivity, and the child(fragment 2) needs to be a fragmentActivity to have the tabs.. some idea?Christine
Oh but wait, you can just put 2 fragment into a fragment without fragmentActivity, you know ? Or maybe you have your reasons to do it...Voss
C
0

After Read some examples, you cant have a FragmentActivity inside a fragmentActivity. Is not necesary to have two fragments and this need be a FragmentPageAdapter... i only need to do this.

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

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:gravity="center"
        android:measureWithLargestChild="true"
        android:orientation="horizontal" >

<Button
            android:id="@+id/first"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="First" >
        </Button>

<Button
            android:id="@+id/last"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Last" >
</Button>
</LinearLayout>

Source: http://www.truiton.com/2013/05/android-fragmentpageradapter-example/

Christine answered 30/9, 2013 at 16:1 Comment(0)
C
0

I'm use ViewPager2 in a Fragment and find it works fine:

public class MyViewPagerAdapter extends FragmentStateAdapter {

public MyViewPagerAdapter (@NonNull FragmentActivity fragmentActivity) {
    super(fragmentActivity);
}

@NonNull
@Override
public Fragment createFragment(int position) {
    switch (position){
        case 0:
            return new Fragment1();
        case 1:
            return new Fragment2();
        default:
            return new Fragment1();
    }
}

@Override
public int getItemCount() {
    return 2;
}

}

And create:

MyViewPagerAdapter myViewPagerAdapter = new MyViewPagerAdapter ((FragmentActivity) context);
    viewPager.setAdapter(myViewPagerAdapter);
    viewPager.setUserInputEnabled(true);
Clearing answered 3/1 at 8:32 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Sikes

© 2022 - 2024 — McMap. All rights reserved.