FragmentPagerAdapter

public abstract class FragmentPagerAdapter extends PagerAdapter

Object
   ↳ PagerAdapter
     ↳ FragmentPagerAdapter

Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter.

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 FragmentPagerSupport 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 FragmentPagerAdapter {
        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 RESUMED state.

static final @NonNull int

This field is deprecated.

This behavior relies on the deprecated setUserVisibleHint API.

Public methods

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

Remove a page for the given position.

@Override @NonNull void

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

abstract @NonNull Fragment
getItem(@NonNull int position)

Return the Fragment associated with a specified position.

@NonNull long
getItemId(@NonNull int position)

Return a unique identifier for the item at the given position.

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

Create the page for the given position.

@Override @NonNull boolean

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

@Override @NonNull void

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

@Override @Nullable 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.

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

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.

@Override @NonNull void

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

Inherited methods

From class PagerAdapter
@NonNull void
destroyItem(
    @NonNull View container,
    @NonNull int position,
    @NonNull Object object
)

This method is deprecated.

Use destroyItem

@NonNull void

This method is deprecated.

Use finishUpdate

abstract @NonNull int

Return the number of views available.

@NonNull int

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

@Nullable CharSequence
getPageTitle(@NonNull int position)

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

@NonNull float
getPageWidth(@NonNull int position)

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

@NonNull Object
instantiateItem(@NonNull View container, @NonNull int position)

This method is deprecated.

Use instantiateItem

@NonNull void

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

@NonNull void

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

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

This method is deprecated.

Use setPrimaryItem

@NonNull void
startUpdate(@NonNull View container)

This method is deprecated.

Use startUpdate

@NonNull void

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

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 RESUMED state. All other Fragments are capped at STARTED.

See also
FragmentPagerAdapter

#FragmentPagerAdapter(FragmentManager, int)

BEHAVIOR_SET_USER_VISIBLE_HINT

@NonNull
public static final @NonNull int BEHAVIOR_SET_USER_VISIBLE_HINT

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

See also
FragmentPagerAdapter

#FragmentPagerAdapter(FragmentManager, int)

Public constructors

FragmentPagerAdapter

public FragmentPagerAdapter(@NonNull FragmentManager fm)

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

Fragments will have setUserVisibleHint called whenever the current Fragment changes.

Parameters
@NonNull FragmentManager fm

fragment manager that will interact with this adapter

FragmentPagerAdapter

public FragmentPagerAdapter(
    @NonNull FragmentManager fm,
    @FragmentPagerAdapter.Behavior @NonNull int behavior
)

Constructor for FragmentPagerAdapter. If BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT is passed in, then only the current Fragment is in the RESUMED state. 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
@NonNull FragmentManager fm

fragment manager that will interact with this adapter

@FragmentPagerAdapter.Behavior @NonNull int behavior

determines if only current fragments are in a resumed state

Public methods

destroyItem

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

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
@NonNull ViewGroup container

The containing View from which the page will be removed.

@NonNull int position

The page position to be removed.

@NonNull Object object

The same object that was returned by instantiateItem.

finishUpdate

@Override
@NonNull
public @Override void finishUpdate(@NonNull ViewGroup container)

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
@NonNull ViewGroup container

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

getItem

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

Return the Fragment associated with a specified position.

getItemId

@NonNull
public long getItemId(@NonNull int position)

Return a unique identifier for the item at the given position.

The default implementation returns the given position. Subclasses should override this method if the positions of items can change.

Parameters
@NonNull int position

Position within this adapter

Returns
long

Unique identifier for the item at position

instantiateItem

@NonNull
@Override
public @Override Object