FragmentStatePagerAdapter

Added in 1.1.0
Deprecated in 1.3.0

abstract class FragmentStatePagerAdapter : PagerAdapter


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

const Int

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

const Int

This property is deprecated.

This behavior relies on the deprecated setUserVisibleHint API.

Public functions

Unit
destroyItem(container: ViewGroup, position: Int, object: Any)

Remove a page for the given position.

Unit
finishUpdate(container: ViewGroup)

Called when the a change in the shown pages has been completed.

abstract Fragment
getItem(position: Int)

Return the Fragment associated with a specified position.

Any
instantiateItem(container: ViewGroup, position: Int)

Create the page for the given position.

Boolean
isViewFromObject(view: View, object: Any)

Determines whether a page View is associated with a specific key object as returned by instantiateItem.

Unit
restoreState(state: Parcelable?, loader: ClassLoader?)

Restore any instance state associated with this adapter and its pages that was previously saved by saveState.

Parcelable?

Save any instance state associated with this adapter and its pages that should be restored if the current UI state needs to be reconstructed.

Unit
setPrimaryItem(container: ViewGroup, position: Int, object: Any)

Called to inform the adapter of which item is currently considered to be the "primary", that is the one show to the user as the current page.

Unit
startUpdate(container: ViewGroup)

Called when a change in the shown pages is going to start being made.

Inherited Constants

From androidx.viewpager.widget.PagerAdapter
const Int
const Int

Inherited functions

From androidx.viewpager.widget.PagerAdapter
Unit
destroyItem(container: View, position: Int, object: Any)

This function is deprecated.

Use destroyItem

Unit
finishUpdate(container: View)

This function is deprecated.

Use finishUpdate

abstract Int

Return the number of views available.

Int

Called when the host view is attempting to determine if an item's position has changed.

CharSequence?
getPageTitle(position: Int)

This method may be called by the ViewPager to obtain a title string to describe the specified page.

Float
getPageWidth(position: Int)

Returns the proportional width of a given page as a percentage of the ViewPager's measured width from (0.f-1.f]

Any
instantiateItem(container: View, position: Int)

This function is deprecated.

Use instantiateItem

Unit

This method should be called by the application if the data backing this adapter has changed and associated views should update.

Unit

Register an observer to receive callbacks related to the adapter's data changing.

Unit
setPrimaryItem(container: View, position: Int, object: Any)

This function is deprecated.

Use setPrimaryItem

Unit
startUpdate(container: View)

This function is deprecated.

Use startUpdate

Unit

Unregister an observer from callbacks related to the adapter's data changing.

Constants

BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT

Added in 1.1.0
Deprecated in 1.3.0
const val BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT = 1: Int

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

BEHAVIOR_SET_USER_VISIBLE_HINT

Added in 1.1.0
Deprecated in 1.1.0
const val BEHAVIOR_SET_USER_VISIBLE_HINT = 0: Int

Indicates that setUserVisibleHint will be called when the current fragment changes.

Public constructors

FragmentStatePagerAdapter

Added in 1.1.0
Deprecated in 1.1.0
FragmentStatePagerAdapter(fm: FragmentManager)

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 setUserVisibleHint called whenever the current Fragment changes.

Parameters
fm: FragmentManager

fragment manager that will interact with this adapter

FragmentStatePagerAdapter

Added in 1.1.0
Deprecated in 1.3.0
FragmentStatePagerAdapter(
    fm: FragmentManager,
    @FragmentStatePagerAdapter.Behavior behavior: Int
)

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

Parameters
fm: FragmentManager

fragment manager that will interact with this adapter

@FragmentStatePagerAdapter.Behavior behavior: Int

determines if only current fragments are in a resumed state

Public functions

destroyItem

fun destroyItem(container: ViewGroup, position: Int, object: Any): Unit

Remove a page for the given position. The adapter is responsible for removing the view from its container, although it only must ensure this is done by the time it returns from finishUpdate.

Parameters
container: ViewGroup

The containing View from which the page will be removed.

position: Int

The page position to be removed.

object: Any

The same object that was returned by instantiateItem.

finishUpdate

fun finishUpdate(container: ViewGroup): Unit

Called when the a change in the shown pages has been completed. At this point you must ensure that all of the pages have actually been added or removed from the container as appropriate.

Parameters
container: ViewGroup

The containing View which is displaying this adapter's page views.

getItem

Added in 1.1.0
Deprecated in 1.3.0
abstract fun getItem(position: Int): Fragment

Return the Fragment associated with a specified position.

instantiateItem

fun instantiateItem(container: ViewGroup, position: Int): Any

Create the page for the given position. The adapter is responsible for adding the view to the container given here, although it only must ensure this is done by the time it returns from finishUpdate.

Parameters
container: ViewGroup

The containing View in which the page will be shown.

position: Int

The page position to be instantiated.

Returns
Any

Returns an Object representing the new page. This does not need to be a View, but can be some other container of the page.

isViewFromObject

Added in 1.1.0
Deprecated in 1.3.0
fun isViewFromObject(view: View, object: Any): Boolean

Determines whether a page View is associated with a specific key object as returned by instantiateItem. This method is required for a PagerAdapter to function properly.

Parameters
view: View

Page View to check for association with object

object: Any

Object to check for association with view

Returns
Boolean

true if view is associated with the key object object

restoreState

fun restoreState(state: Parcelable?, loader: ClassLoader?): Unit

Restore any instance state associated with this adapter and its pages that was previously saved by saveState.

Parameters
state: Parcelable?

State previously saved by a call to saveState

loader: ClassLoader?

A ClassLoader that should be used to instantiate any restored objects

saveState

fun saveState(): Parcelable?

Save any instance state associated with this adapter and its pages that should be restored if the current UI state needs to be reconstructed.

Returns
Parcelable?

Saved state for this adapter

setPrimaryItem

fun setPrimaryItem(container: ViewGroup, position: Int, object: Any): Unit

Called to inform the adapter of which item is currently considered to be the "primary", that is the one show to the user as the current page. This method will not be invoked when the adapter contains no items.

Parameters
container: ViewGroup

The containing View from which the page will be removed.

position: Int

The page position that is now the primary.

object: Any

The same object that was returned by instantiateItem.

startUpdate

fun startUpdate(container: ViewGroup): Unit

Called when a change in the shown pages is going to start being made.

Parameters
container: ViewGroup

The containing View which is displaying this adapter's page views.