FragmentStatePagerAdapter

public abstract class

FragmentStatePagerAdapter

extends PagerAdapter

java.lang.Object
   ? android.support.v4.view.PagerAdapter
     ? android.support.v4.app.FragmentStatePagerAdapter

Class Overview



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(int) and getCount() to have a working adapter.

Here is an example implementation of a pager containing fragments of lists:

public class FragmentStatePagerSupport extends Activity {    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(getFragmentManager());

        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() {            public void onClick(View v) {                mPager.setCurrentItem(0);            }        });        button = (Button)findViewById(R.id.goto_last);        button.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                mPager.setCurrentItem(NUM_ITEMS-1);            }        });    }

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

        @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 onActivityCreated(Bundle savedInstanceState) {            super.onActivityCreated(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_pager resource 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">

    <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: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_list resource 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 emtpy -->        <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


[Expand]

Inherited Constants

From class android.support.v4.view.PagerAdapter

Public Constructors
  FragmentStatePagerAdapter(FragmentManager fm)
Public Methods
void destroyItem(ViewGroup container, int position, Object object)

Remove a page for the given position.

void finishUpdate(ViewGroup container)

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

abstract Fragment getItem(int position)

Return the Fragment associated with a specified position.

Object instantiateItem(ViewGroup container, int position)

Create the page for the given position.

boolean isViewFromObject(View view, Object object)

Determines whether a page View is associated with a specific key object as returned by instantiateItem(ViewGroup, int).

void restoreState(Parcelable state, ClassLoader loader)

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

Parcelable saveState()

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

void setPrimaryItem(ViewGroup container, int position, 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.

void startUpdate(ViewGroup container)

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

[Expand]

Inherited Methods

 From class android.support.v4.view.PagerAdapter

 From class java.lang.Object

Public Constructors


public FragmentStatePagerAdapter (FragmentManager fm)

Public Methods


public void destroyItem (ViewGroup container, int position, 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(ViewGroup).

Parameters
container The containing View from which the page will be removed.
position The page position to be removed.
object The same object that was returned by instantiateItem(View, int).

public void finishUpdate (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
container The containing View which is displaying this adapter‘s page views.

public abstract Fragment getItem (int position)

Return the Fragment associated with a specified position.

public Object instantiateItem (ViewGroup container, int position)

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(ViewGroup).

Parameters
container The containing View in which the page will be shown.
position The page position to be instantiated.
Returns
  • Returns an Object representing the new page. This does not need to be a View, but can be some other container of the page.

public boolean isViewFromObject (View view, Object object)

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

Parameters
view Page View to check for association with object
object Object to check for association with view
Returns
  • true if view is associated with the key object object

public void restoreState (Parcelable state, ClassLoader loader)

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

Parameters
state State previously saved by a call to saveState()
loader A ClassLoader that should be used to instantiate any restored objects

public Parcelable saveState ()

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
  • Saved state for this adapter

public void setPrimaryItem (ViewGroup container, int position, 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.

Parameters
container The containing View from which the page will be removed.
position The page position that is now the primary.
object The same object that was returned by instantiateItem(View, int).

public void startUpdate (ViewGroup container)

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

Parameters
container The containing View which is displaying this adapter‘s page views.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.

Android 4.4 r1 — 28 Aug 2014 0:14

About Android  |  Legal  |  Support

时间: 2024-08-30 03:43:31

FragmentStatePagerAdapter的相关文章

FragmentPagerAdapter与FragmentStatePagerAdapter区别

在一个 Android 应用中,我使用 FragmentPagerAdapter 来处理多 Fragment 页面的横向滑动.不过我碰到了一个问题,即当 Fragment 对应的数据集发生改变时,我希望能够通过调用 mAdapter.notifyDataSetChanged() 来触发 Fragment 页面使用新的数据调整或重新生成其内容,可是当我调用 notifyDataSetChanged() 后,发现什么都没发生. 搜索之后发现不止我一个人碰到这个问题,大家给出的解决办法五花八门,有些确

FragmentPagerAdapter和FragmentStatePagerAdapter区别?

FragmentPagerAdapter:对于不再需要的fragment,选择调用detach方法,仅销毁视图,并不会销毁fragment实例.FragmentStatePagerAdapter:会销毁不再需要的fragment,当当前事务提交以后,会彻底的将fragmeng从当前Activity的FragmentManager中移除,state标明,销毁时,会将其onSaveInstanceState(Bundle outState)中的bundle信息保存下来,当用户切换回来,可以通过该bu

FragmentStatePagerAdapter的使用

1.两点 getItemPosition的覆写使notifyDataSetChanged();会根据数据源的变动更新,不过是全部重新加载,和ListView不一样 为了从外界(Activity)操作当前的fragment界面,使用了SparseArray<WeakReference<Fragment>>将当前的fragment实例存起来. public class WillPagerAdapter extends FragmentStatePagerAdapter { // Spa

FragmentPagerAdapter与FragmentStatePagerAdapter差异

平常使用的FragmentPagerAdapter和FragmentStatePagerAdapter来自android.support.v4.app包用来构建ViewPager.FragmentPagerAdapter更多的用于少量界面的ViewPager,比如Tab.划过的fragment会保存在内存中,尽管已经划过.而FragmentStatePagerAdapter和ListView有点类似,会保存当前界面,以及下一个界面和上一个界面(如果有),最多保存3个,其他会被销毁掉.要注意的是F

FragmentStatePagerAdapter和FragmentPagerAdapter区别

1.如果ViewPager中加载的是Fragment,则提供的Adpater可以继承于具体的:FragmentStatePagerAdapter或FragmentPagerAdapter 2.FragmentStatePagerAdapter:适用于ViewPager中加载的Fragment过多,会根据最近最少使用算法,实现内存中Fragment的清理,避免溢出 3.FragmentPagerAdapter:适用于ViewPager中加载的Fragment不多时,系统不会清理已经加载的Fragm

109、FragmentPagerAdapter与FragmentStatePagerAdapter区别

x 在一个 Android 应用中,我使用 FragmentPagerAdapter 来处理多 Fragment 页面的横向滑动.不过我碰到了一个问题,即当 Fragment 对应的数据集发生改变时,我希望能够通过调用 mAdapter.notifyDataSetChanged() 来触发 Fragment 页面使用新的数据调整或重新生成其内容,可是当我调用 notifyDataSetChanged() 后,发现什么都没发生. 搜索之后发现不止我一个人碰到这个问题,大家给出的解决办法五花八门,有

TabLayout+Fragment+ViewPager+FragmentStatePagerAdapter实现Tab标签

首先来看下实现的效果吧: 最近在项目中实现这个效果的时候.尽管自己磕磕绊绊的实现了,可是知识确实模模糊糊的,今天天气异常的冷,在加上这个知识不太熟练,实在是没有心情进行接下来的计划,干脆借着这个时间,好好的整理一下这个实现方式.也在次总结一下,记忆更加深刻. TabLayout简单介绍 在2015年的Google I/O大会上,Google公布的新的Android Support Design库,里面也包括了几个新的控件,那么TabLayout就是当中一个.使用该组件我们能够非常轻松的实现Tab

FragmentStatePagerAdapter分页

[ ViewPager ] ViewPager 如其名所述,是负责翻页的一个 View.准确说是一个 ViewGroup,包含多个 View 页,在手指横向滑动屏幕时,其负责对 View 进行切换.为了生成这些 View 页,需要提供一个 PagerAdapter 来进行和数据绑定以及生成最终的 View 页. setAdapter() ViewPager 通过 setAdapter() 来建立与 PagerAdapter 的联系.这个联系是双向的,一方面,ViewPager 会拥有 Pager

FragmentPagerAdapter和FragmentStatePagerAdapter的区别

FragmentPagerAdapter 1:简单的介绍: 该类内的每一个生成的 Fragment 都将保存在内存之中,因此适用于那些相对静态的页,数量也比较少的那种:如果需要处理有很多页,并且数据动态性较大.占用内存较多的情况,应该使用FragmentStatePagerAdapter 2:重写的几个方法: getItem() 该类中新增的一个虚函数.函数的目的为生成新的 Fragment 对象.重载该函数时需要注意这一点.在需要时,该函数将被 instantiateItem() 所调用. 如

ViewPager适配器学习记录( pageAdapter和FragmentPagerAdapter/FragmentStatePagerAdapter))

1.概述 ViewPager,顾名思义实现控件的滚动功能,是Support-v4的包中类,使用前要先导包.使用的时候跟listView有点相似,需要设置对应的适配器,通常有俩大类 [pageAdapter] [FragmentPagerAdapter/FragmentStatePagerAdapter] fragment有着自己的生命周期,谷歌官方也推荐使用ViewPage+fragment的形式,一般简单的也可以使用ViewPage+pageAdapter形式 这里用这俩种适配器来搭个框架学习