Android 开发之ViewPage官方文档学习笔记

以下为官网的官方文档,我将从翻译该文档开始学习。

ViewPager

extends ViewGroup

java.lang.Object

   ↳
android.view.View

   ↳
android.view.ViewGroup

   ↳
android.support.v4.view.ViewPager

Class Overview

Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows.

允许用户左或者由翻转页面去展示数据的布局管理其。你提供一个实现了PagerAdapter的类去生成视图显示的页面。

Note this class is currently under early design and development. The API will likely change in later updates of the compatibility library, requiring changes to the source code of apps when they are compiled against the newer version.

注意这个类是当前早起设计和开发的。这个API可能会在后面的兼容库的更新中改变。再一次编译新版本的应用程序时需要更改这个源代码。

ViewPager is most often used in conjunction with Fragment, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These areFragmentPagerAdapter and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.

ViewPager常常通过与Fragment结合使用。这种方式便于提供和管理每个页面的生命周期。这是一个标准的对于在viewPager上使用fragment的适配器的实现,覆盖了最常见的案例。在FragmentPagerAdapter和FragmentStatePagerAdapter这两个类,每一个都有如何使用ViewPager和Fragment去构建一个完成的用户界面的简单代码的展示。

For more information about how to use ViewPager, read Creating Swipe Views with Tabs.

对于更多如何去使用ViewPager的信息,请阅读Creating Swipe View With Tabs(创建华东的视图选卡)

Below is a more complicated example of ViewPager, using it in conjunction with ActionBar tabs. You can find other examples of using ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code.

一下是一个更加全面的使用ViewPager结合ActionBar选项卡的例子。在API 4+ supportdemos 和api13+ support demos实例代码中你可以找到一些其他的使用viewPager的例子

public class ActionBarTabsPager extends Activity {
    ViewPager mViewPager;
    TabsAdapter mTabsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mViewPager = new ViewPager(this);
        mViewPager.setId(R.id.pager);
        setContentView(mViewPager);

        final ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

        mTabsAdapter = new TabsAdapter(this, mViewPager);
        mTabsAdapter.addTab(bar.newTab().setText("Simple"),
                CountingFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("List"),
                FragmentPagerSupport.ArrayListFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("Cursor"),
                CursorFragment.class, null);

        if (savedInstanceState != null) {
            bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }

    /**
     * This is a helper class that implements the management of tabs and all
     * details of connecting a ViewPager with associated TabHost.  It relies on a
     * trick.  Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show.  This is not sufficient for switching
     * between pages.  So instead we make the content part of the tab host
     * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
     * view to show as the tab content.  It listens to changes in tabs, and takes
     * care of switch to the correct paged in the ViewPager whenever the selected
     * tab changes.
     */
    public static class TabsAdapter extends FragmentPagerAdapter
            implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final ActionBar mActionBar;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(Class<?> _class, Bundle _args) {
                clss = _class;
                args = _args;
            }
        }

        public TabsAdapter(Activity activity, ViewPager pager) {
            super(activity.getFragmentManager());
            mContext = activity;
            mActionBar = activity.getActionBar();
            mViewPager = pager;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
            TabInfo info = new TabInfo(clss, args);
            tab.setTag(info);
            tab.setTabListener(this);
            mTabs.add(info);
            mActionBar.addTab(tab);
            notifyDataSetChanged();
        }

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

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            mActionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            Object tag = tab.getTag();
            for (int i=0; i<mTabs.size(); i++) {
                if (mTabs.get(i) == tag) {
                    mViewPager.setCurrentItem(i);
                }
            }
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }
    }
}
Summary

概念


Nested Classes

class
ViewPager.LayoutParams
Layout parameters that should be supplied for views added to a ViewPager.

在视图添加到ViewPager时提供布局参数的支持。

interface
ViewPager.OnPageChangeListener
Callback interface for responding to changing state of the selected page.

选择页面是相应这个改变状态的回调借口。

interface
ViewPager.PageTransformer
A PageTransformer is invoked whenever a visible/attached page is scrolled.

可见的页面或则附加页面是滚动的时候被调用

class
ViewPager.SavedState
This is the persistent state that is saved by ViewPager.

被ViewPager持久化保存的一个状态

class
ViewPager.SimpleOnPageChangeListener
Simple implementation of the ViewPager.OnPageChangeListener interface with stub implementations of each method.

每一个ViewPager.OnPageChangeListener的存根的接口简单的实现

Constants

int
SCROLL_STATE_DRAGGING
Indicates that the pager is currently being dragged by the user.

标志当前被用户拖拽的页面

int
SCROLL_STATE_IDLE
Indicates that the pager is in an idle, settled state.

标识这被闲置的页面

int
SCROLL_STATE_SETTLING
Indicates that the pager is in the process of settling to a final position.

标识

Public Constructors

构造方法

ViewPager(Context context)

ViewPager(Context context, AttributeSet attrs)

Public Methods

void
, int, int)">addFocusables(ArrayList<View> views, int direction, int focusableMode)

We only want the current page that is being shown to be focusable.

我们只需要当前的页面称为焦点被显示。

void
addOnPageChangeListener(ViewPager.OnPageChangeListener listener)

Add a listener that will be invoked whenever the page changes or is incrementally scrolled.

增加一个监听者,不管页面改变或者递增的滚动都会被调用。

void
)">addTouchables(ArrayList<View> views)

We only want the current page that is being shown to be touchable.

我们只想着当前的页面是被可触摸的展示。

void
addView(View child, int index, ViewGroup.LayoutParams params)

Adds a child view with the specified layout parameters.

用指定的布局参数增加一个子视图。

boolean
arrowScroll(int direction)

boolean
beginFakeDrag()

Start a fake drag of the pager.

就是虚拟拖拽一个页面。

boolean
canScrollHorizontally(int direction)

Check if this view can be scrolled horizontally in a certain direction.

检查视图是否可以被水平方向滚动

void
clearOnPageChangeListeners()

Remove all listeners that are notified of any changes in scroll state or position.

删除所有在滚动状态或者位置改变时被通知的监听者。

void
computeScroll()

Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary.

要求子类更新mScrollX和mScrollY如有需要将被父类去调用。

boolean
dispatchKeyEvent(KeyEvent event)

Dispatch a key event to the next view on the focus path.

boolean
dispatchPopulateAccessibilityEvent(AccessibilityEvent event)

Dispatches an AccessibilityEvent to the View first and then to its children for adding their text content to the event.

void
draw(Canvas canvas)

Manually render this view (and all of its children) to the given Canvas.

void
endFakeDrag()

End a fake drag of the pager.

boolean
executeKeyEvent(KeyEvent event)

You can call this function yourself to have the scroll view perform scrolling from a key event, just as if the event had been dispatched to it by the view hierarchy.

void
fakeDragBy(float xOffset)

Fake drag by an offset in pixels.

ViewGroup.LayoutParams
generateLayoutParams(AttributeSet attrs)

Returns a new set of layout parameters based on the supplied attributes set.

PagerAdapter
getAdapter()

Retrieve the current adapter supplying pages.

int
getCurrentItem()

int
getOffscreenPageLimit()

Returns the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state.

int
getPageMargin()

Return the margin between pages.

boolean
isFakeDragging()

Returns true if a fake drag is in progress.

boolean
onInterceptTouchEvent(MotionEvent ev)

Implement this method to intercept all touch screen motion events.

实现这个方法去拦截所有屏幕的触摸事件。

void
onRestoreInstanceState(Parcelable state)

Hook allowing a view to re-apply a representation of its internal state that had previously been generated byonSaveInstanceState().

Parcelable
onSaveInstanceState()

Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state.

boolean
onTouchEvent(MotionEvent ev)

Implement this method to handle touch screen motion events.

实现该防区去控制屏幕的触摸事件。

void
removeOnPageChangeListener(ViewPager.OnPageChangeListener listener)

Remove a listener that was previously added via addOnPageChangeListener(OnPageChangeListener).

void
removeView(View view)

Note: do not invoke this method from draw(android.graphics.Canvas),onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

void
setAdapter(PagerAdapter adapter)

Set a PagerAdapter that will supply views for this pager as needed.

void
setCurrentItem(int item, boolean smoothScroll)

Set the currently selected page.

设置当前被选中的页面

void
setCurrentItem(int item)

Set the currently selected page.

设置当前被选中的页面

void
setOffscreenPageLimit(int limit)

Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state.

void
setOnPageChangeListener(ViewPager.OnPageChangeListener listener)

This method is deprecated. Use addOnPageChangeListener(OnPageChangeListener) andremoveOnPageChangeListener(OnPageChangeListener) instead.

void
setPageMargin(int marginPixels)

Set the margin between pages.

设置两个页面的间隙

void
setPageMarginDrawable(int resId)

Set a drawable that will be used to fill the margin between pages.

void
setPageMarginDrawable(Drawable d)

Set a drawable that will be used to fill the margin between pages.

void
setPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer)

Set a ViewPager.PageTransformer that will be called for each attached page whenever the scroll position is changed.

转载于:https://my.oschina.net/zaizaiangels/blog/533912

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值