{% setvar book_path %}/reference/androidx/_book.yaml{% endsetvar %} {% include "_shared/_reference-head-tags.html" %}

FragmentStatePagerAdapter

{% setvar page_path %}androidx/fragment/app/FragmentStatePagerAdapter.html{% endsetvar %} {% setvar can_switch %}1{% endsetvar %} {% include "reference/_java_switcher2.md" %}

public abstract class FragmentStatePagerAdapter


Implementation of PagerAdapter that uses a Fragment to manage each page. This class also handles saving and restoring of fragment's state.

This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.

When using FragmentPagerAdapter the host ViewPager must have a valid ID set.

Subclasses only need to implement getItem and getCount to have a working adapter.

Here is an example implementation of a pager containing fragments of lists:
public class FragmentStatePagerSupport extends FragmentActivity {
    static final int NUM_ITEMS = 10;

    MyAdapter mAdapter;

    ViewPager mPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_pager);

        mAdapter = new MyAdapter(getSupportFragmentManager());

        mPager = (ViewPager)findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.goto_first);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mPager.setCurrentItem(0);
            }
        });
        button = (Button)findViewById(R.id.goto_last);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mPager.setCurrentItem(NUM_ITEMS-1);
            }
        });
    }

    public static class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        }

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

        @Override
        public Fragment getItem(int position) {
            return ArrayListFragment.newInstance(position);
        }
    }

    public static class ArrayListFragment extends ListFragment {
        int mNum;

        /**
         * Create a new instance of CountingFragment, providing "num"
         * as an argument.
         */
        static ArrayListFragment newInstance(int num) {
            ArrayListFragment f = new ArrayListFragment();

            // Supply num input as an argument.
            Bundle args = new Bundle();
            args.putInt("num", num);
            f.setArguments(args);

            return f;
        }

        /**
         * When creating, retrieve this instance's number from its arguments.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mNum = getArguments() != null ? getArguments().getInt("num") : 1;
        }

        /**
         * The Fragment's UI is just a simple text view showing its
         * instance number.
         */
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
            View tv = v.findViewById(R.id.text);
            ((TextView)tv).setText("Fragment #" + mNum);
            return v;
        }

        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_1, Cheeses.sCheeseStrings));
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            Log.i("FragmentList", "Item clicked: " + id);
        }
    }
}
The R.layout.fragment_pagerresource of the top-level fragment is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical" android:padding="4dip"
              android:gravity="center_horizontal"
              android:layout_width="match_parent" android:layout_height="match_parent">

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

    <LinearLayout android:orientation="horizontal"
                  android:gravity="center" android:measureWithLargestChild="true"
                  android:layout_width="match_parent" android:layout_height="wrap_content"
                  android:layout_weight="0">
        <Button android:id="@+id/goto_first"
                android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:text="@string/first">
        </Button>
        <Button android:id="@+id/goto_last"
                android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:text="@string/last">
        </Button>
    </LinearLayout>
</LinearLayout>
The R.layout.fragment_pager_listresource containing each individual fragment's layout is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@android:drawable/gallery_thumb">

    <TextView android:id="@+id/text"
              android:layout_width="match_parent" android:layout_height="wrap_content"
              android:gravity="center_vertical|center_horizontal"
              android:textAppearance="?android:attr/textAppearanceMedium"
              android:text="@string/hello_world"/>

    <!-- The frame layout is here since we will be showing either
    the empty view or the list view.  -->
    <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="1" >
        <!-- Here is the list. Since we are using a ListActivity, we
             have to call it "@android:id/list" so ListActivity will
             find it -->
        <ListView android:id="@android:id/list"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:drawSelectorOnTop="false"/>

        <!-- Here is the view to show if the list is empty -->
        <TextView android:id="@android:id/empty"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:textAppearance="?android:attr/textAppearanceMedium"
                  android:text="No items."/>

    </FrameLayout>

</LinearLayout>

Summary

Constants

static final @NonNull int

Indicates that only the current fragment will be in the Lifecycle.State#RESUMED state.

static final @NonNull int

This field is deprecated.

This behavior relies on the deprecated Fragment#setUserVisibleHint(boolean) API.

Public constructors

This method is deprecated.

use FragmentStatePagerAdapter with BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT

FragmentStatePagerAdapter(
    @NonNull FragmentManager fm,
    @NonNull int behavior
)

Constructor for FragmentStatePagerAdapter.

Public methods

@NonNull void
destroyItem(
    @NonNull ViewGroup container,
    @NonNull int position,
    @NonNull Object object
)
@NonNull void
finishUpdate(@NonNull ViewGroup container)
abstract @NonNull Fragment
getItem(@NonNull int position)

Return the Fragment associated with a specified position.

@NonNull Object
instantiateItem(@NonNull ViewGroup container, @NonNull int position)
@NonNull boolean
isViewFromObject(@NonNull View view, @NonNull Object object)
@NonNull void
restoreState(@Nullable Parcelable state, @Nullable ClassLoader loader)
@Nullable Parcelable
@NonNull void
setPrimaryItem(
    @NonNull ViewGroup container,
    @NonNull int position,
    @NonNull Object object
)
@NonNull void
startUpdate(@NonNull ViewGroup container)

Constants

BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT

@NonNull
public static final @NonNull int BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT

Indicates that only the current fragment will be in the Lifecycle.State#RESUMED state. All other Fragments are capped at Lifecycle.State#STARTED.

See also
FragmentStatePagerAdapter

#FragmentStatePagerAdapter(FragmentManager, int)

BEHAVIOR_SET_USER_VISIBLE_HINT

@NonNull
public static final @NonNull int BEHAVIOR_SET_USER_VISIBLE_HINT

Indicates that Fragment#setUserVisibleHint(boolean) will be called when the current fragment changes.

See also
FragmentStatePagerAdapter

#FragmentStatePagerAdapter(FragmentManager, int)

Public constructors

FragmentStatePagerAdapter

@NonNull
public FragmentStatePagerAdapter(@NonNull FragmentManager fm)

Constructor for FragmentStatePagerAdapter that sets the fragment manager for the adapter. This is the equivalent of calling FragmentStatePagerAdapter and passing in BEHAVIOR_SET_USER_VISIBLE_HINT.

Fragments will have Fragment#setUserVisibleHint(boolean) called whenever the current Fragment changes.

Parameters
@NonNull FragmentManager fm

fragment manager that will interact with this adapter

FragmentStatePagerAdapter

@NonNull
public FragmentStatePagerAdapter(
    @NonNull FragmentManager fm,
    @NonNull int behavior
)

Constructor for FragmentStatePagerAdapter. If BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT is passed in, then only the current Fragment is in the Lifecycle.State#RESUMED state, while all other fragments are capped at Lifecycle.State#STARTED. If BEHAVIOR_SET_USER_VISIBLE_HINT is passed, all fragments are in the Lifecycle.State#RESUMED state and there will be callbacks to Fragment#setUserVisibleHint(boolean).

Parameters
@NonNull FragmentManager fm

fragment manager that will interact with this adapter

@NonNull int behavior

determines if only current fragments are in a resumed stateValue is BEHAVIOR_SET_USER_VISIBLE_HINT, or BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT

Public methods

destroyItem

@NonNull
public void destroyItem(
    @NonNull ViewGroup container,
    @NonNull int position,
    @NonNull Object object
)

finishUpdate

@NonNull
public void finishUpdate(@NonNull ViewGroup container)

getItem

@NonNull
public abstract Fragment getItem(@NonNull int position)

Return the Fragment associated with a specified position.

instantiateItem

@NonNull
public Object instantiateItem(@NonNull ViewGroup container, @NonNull int position)

isViewFromObject

@NonNull
public boolean isViewFromObject(@NonNull View view, @NonNull Object object)

restoreState

@NonNull
public void restoreState(@Nullable Parcelable state, @Nullable ClassLoader loader)

saveState

@Nullable
@NonNull
public Parcelable saveState()

setPrimaryItem

@NonNull
public void setPrimaryItem(
    @NonNull ViewGroup container,
    @NonNull int position,
    @NonNull Object object
)

startUpdate

@NonNull
public void startUpdate(@NonNull ViewGroup container)