重所周知,viewpager是制作轮播图的基本构件,下面是API介绍

ViewPagerextends ViewGroupjava.lang.Object   ↳    android.view.View       ↳    android.view.ViewGroup           ↳    android.support.v4.view.ViewPagerClass OverviewLayout 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.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.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 are FragmentPagerAdapter and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.Here is a more complicated example of ViewPager, using it in conjuction with ActionBar tabs. You can find other examples of using ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code.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 mTabs = new ArrayList();        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; iif (mTabs.get(i) == tag) {                    mViewPager.setCurrentItem(i);                }            }        }        @Override        public void onTabUnselected(Tab tab, FragmentTransaction ft) {        }        @Override        public void onTabReselected(Tab tab, FragmentTransaction ft) {        }    }}SummaryNested Classesclass   ViewPager.LayoutParams  Layout parameters that should be supplied for views added to a 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. class   ViewPager.SimpleOnPageChangeListener    Simple implementation of the ViewPager.OnPageChangeListener interface with stub implementations of each method. [Expand]Inherited XML AttributesFrom class android.view.ViewGroupFrom class android.view.ViewConstantsint 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.[Expand]Inherited ConstantsFrom class android.view.ViewGroupFrom class android.view.View[Expand]Inherited FieldsFrom class android.view.ViewPublic ConstructorsViewPager(Context context)ViewPager(Context context, AttributeSet attrs)Public Methodsvoid    addFocusables(ArrayList views, int direction, int focusableMode)We only want the current page that is being shown to be focusable.void    addTouchables(ArrayList 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    computeScroll()Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary.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 by onSaveInstanceState().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    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)Set a listener that will be invoked whenever the page changes or is incrementally scrolled.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.Protected Methodsboolean canScroll(View v, boolean checkV, int dx, int x, int y)Tests scrollability within child views of v given a delta of dx.boolean checkLayoutParams(ViewGroup.LayoutParams p)void    drawableStateChanged()This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.ViewGroup.LayoutParams  generateDefaultLayoutParams()Returns a set of default layout parameters.ViewGroup.LayoutParams  generateLayoutParams(ViewGroup.LayoutParams p)Returns a safe set of layout parameters based on the supplied layout params.int getChildDrawingOrder(int childCount, int i)Returns the index of the child to draw for this iteration.void    onAttachedToWindow()This is called when the view is attached to a window.void    onDetachedFromWindow()This is called when the view is detached from a window.void    onDraw(Canvas canvas)Implement this to do your drawing.void    onLayout(boolean changed, int l, int t, int r, int b)Called from layout when this view should assign a size and position to each of its children.void    onMeasure(int widthMeasureSpec, int heightMeasureSpec)Measure the view and its content to determine the measured width and the measured height.void    onPageScrolled(int position, float offset, int offsetPixels)This method will be invoked when the current page is scrolled, either as part of a programmatically initiated smooth scroll or a user initiated touch scroll.boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)We only want the current page that is being shown to be focusable.void    onSizeChanged(int w, int h, int oldw, int oldh)This is called during layout when the size of this view has changed.boolean verifyDrawable(Drawable who)If your view subclass is displaying its own Drawable objects, it should override this function and return true for any Drawable it is displaying.[Expand]Inherited Methods From class android.view.ViewGroup From class android.view.View From class java.lang.Object From interface android.graphics.drawable.Drawable.Callback From interface android.view.KeyEvent.Callback From interface android.view.ViewManager From interface android.view.ViewParent From interface android.view.accessibility.AccessibilityEventSourceConstantspublic static final int SCROLL_STATE_DRAGGINGIndicates that the pager is currently being dragged by the user.Constant Value: 1 (0x00000001)public static final int SCROLL_STATE_IDLEIndicates that the pager is in an idle, settled state. The current page is fully in view and no animation is in progress.Constant Value: 0 (0x00000000)public static final int SCROLL_STATE_SETTLINGIndicates that the pager is in the process of settling to a final position.Constant Value: 2 (0x00000002)Public Constructorspublic ViewPager (Context context)public ViewPager (Context context, AttributeSet attrs)Public Methodspublic void addFocusables (ArrayList views, int direction, int focusableMode)We only want the current page that is being shown to be focusable.Parametersviews   Focusable views found so far or null if all we are interested is the number of focusables.direction   The direction of the focus.focusableMode   The type of focusables to be added.public void addTouchables (ArrayList views)We only want the current page that is being shown to be touchable.Parametersviews   Touchable views found so farpublic void addView (View child, int index, ViewGroup.LayoutParams params)Adds a child view with the specified layout parameters.Note: do not invoke this method from draw(android.graphics.Canvas), onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.Parameterschild   the child view to addindex   the position at which to add the childparams  the layout parameters to set on the childpublic boolean arrowScroll (int direction)public boolean beginFakeDrag ()Start a fake drag of the pager.A fake drag can be useful if you want to synchronize the motion of the ViewPager with the touch scrolling of another view, while still letting the ViewPager control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.) Call fakeDragBy(float) to simulate the actual drag motion. Call endFakeDrag() to complete the fake drag and fling as necessary.During a fake drag the ViewPager will ignore all touch events. If a real drag is already in progress, this method will return false.Returnstrue if the fake drag began successfully, false if it could not be started.See AlsofakeDragBy(float)endFakeDrag()public boolean canScrollHorizontally (int direction)Check if this view can be scrolled horizontally in a certain direction.Parametersdirection   Negative to check scrolling left, positive to check scrolling right.Returnstrue if this view can be scrolled in the specified direction, false otherwise.public void computeScroll ()Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary. This will typically be done if the child is animating a scroll using a Scroller object.public boolean dispatchKeyEvent (KeyEvent event)Dispatch a key event to the next view on the focus path. This path runs from the top of the view tree down to the currently focused view. If this view has focus, it will dispatch to itself. Otherwise it will dispatch the next node down the focus path. This method also fires any key listeners.Parametersevent   The key event to be dispatched.ReturnsTrue if the event was handled, false otherwise.public boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event)Dispatches an AccessibilityEvent to the View first and then to its children for adding their text content to the event. Note that the event text is populated in a separate dispatch path since we add to the event not only the text of the source but also the text of all its descendants. A typical implementation will call onPopulateAccessibilityEvent(AccessibilityEvent) on the this view and then call the dispatchPopulateAccessibilityEvent(AccessibilityEvent) on each child. Override this method if custom population of the event text content is required.If an View.AccessibilityDelegate has been specified via calling setAccessibilityDelegate(AccessibilityDelegate) its dispatchPopulateAccessibilityEvent(View, AccessibilityEvent) is responsible for handling this call.Note: Accessibility events of certain types are not dispatched for populating the event text via this method. For details refer to AccessibilityEvent.Parametersevent   The event.ReturnsTrue if the event population was completed.public void draw (Canvas canvas)Manually render this view (and all of its children) to the given Canvas. The view must have already done a full layout before this function is called. When implementing a view, implement onDraw(android.graphics.Canvas) instead of overriding this method. If you do need to override this method, call the superclass version.Parameterscanvas  The Canvas to which the View is rendered.public void endFakeDrag ()End a fake drag of the pager.See AlsobeginFakeDrag()fakeDragBy(float)public 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.Parametersevent   The key event to execute.ReturnsReturn true if the event was handled, else false.public void fakeDragBy (float xOffset)Fake drag by an offset in pixels. You must have called beginFakeDrag() first.ParametersxOffset Offset in pixels to drag by.See AlsobeginFakeDrag()endFakeDrag()public ViewGroup.LayoutParams generateLayoutParams (AttributeSet attrs)Returns a new set of layout parameters based on the supplied attributes set.Parametersattrs   the attributes to build the layout parameters fromReturnsan instance of ViewGroup.LayoutParams or one of its descendantspublic PagerAdapter getAdapter ()Retrieve the current adapter supplying pages.ReturnsThe currently registered PagerAdapterpublic int getCurrentItem ()public 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. Defaults to 1.ReturnsHow many pages will be kept offscreen on either sideSee AlsosetOffscreenPageLimit(int)public int getPageMargin ()Return the margin between pages.ReturnsThe size of the margin in pixelspublic boolean isFakeDragging ()Returns true if a fake drag is in progress.Returnstrue if currently in a fake drag, false otherwise.See AlsobeginFakeDrag()fakeDragBy(float)endFakeDrag()public boolean onInterceptTouchEvent (MotionEvent ev)Implement this method to intercept all touch screen motion events. This allows you to watch events as they are dispatched to your children, and take ownership of the current gesture at any point.Using this function takes some care, as it has a fairly complicated interaction with View.onTouchEvent(MotionEvent), and using it requires implementing that method as well as this one in the correct way. Events will be received in the following order:You will receive the down event here.The down event will be handled either by a child of this view group, or given to your own onTouchEvent() method to handle; this means you should implement onTouchEvent() to return true, so you will continue to see the rest of the gesture (instead of looking for a parent view to handle it). Also, by returning true from onTouchEvent(), you will not receive any following events in onInterceptTouchEvent() and all touch processing must happen in onTouchEvent() like normal.For as long as you return false from this function, each following event (up to and including the final up) will be delivered first here and then to the target's onTouchEvent().If you return true from here, you will not receive any following events: the target view will receive the same event but with the action ACTION_CANCEL, and all further events will be delivered to your onTouchEvent() method and no longer appear here.Parametersev  The motion event being dispatched down the hierarchy.ReturnsReturn true to steal motion events from the children and have them dispatched to this ViewGroup through onTouchEvent(). The current target will receive an ACTION_CANCEL event, and no further messages will be delivered here.public void onRestoreInstanceState (Parcelable state)Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState(). This function will never be called with a null state.Parametersstate   The frozen state that had previously been returned by onSaveInstanceState().public 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. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.Some examples of things you may store here: the current cursor position in a text view (but usually not the text itself since that is stored in a content provider or other persistent storage), the currently selected item in a list view.ReturnsReturns a Parcelable object containing the view's current dynamic state, or null if there is nothing interesting to save. The default implementation returns null.public boolean onTouchEvent (MotionEvent ev)Implement this method to handle touch screen motion events.If this method is used to detect click actions, it is recommended that the actions be performed by implementing and calling performClick(). This will ensure consistent system behavior, including:obeying click sound preferencesdispatching OnClickListener callshandling ACTION_CLICK when accessibility features are enabledParametersev  The motion event.ReturnsTrue if the event was handled, false otherwise.public 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.public void setAdapter (PagerAdapter adapter)Set a PagerAdapter that will supply views for this pager as needed.Parametersadapter Adapter to usepublic void setCurrentItem (int item, boolean smoothScroll)Set the currently selected page.Parametersitem    Item index to selectsmoothScroll    True to smoothly scroll to the new item, false to transition immediatelypublic void setCurrentItem (int item)Set the currently selected page. If the ViewPager has already been through its first layout with its current adapter there will be a smooth animated transition between the current item and the specified item.Parametersitem    Item index to selectpublic 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. Pages beyond this limit will be recreated from the adapter when needed.This is offered as an optimization. If you know in advance the number of pages you will need to support or have lazy-loading mechanisms in place on your pages, tweaking this setting can have benefits in perceived smoothness of paging animations and interaction. If you have a small number of pages (3-4) that you can keep active all at once, less time will be spent in layout for newly created view subtrees as the user pages back and forth.You should keep this limit low, especially if your pages have complex layouts. This setting defaults to 1.Parameterslimit   How many pages will be kept offscreen in an idle state.public void setOnPageChangeListener (ViewPager.OnPageChangeListener listener)Set a listener that will be invoked whenever the page changes or is incrementally scrolled. See ViewPager.OnPageChangeListener.Parameterslistener    Listener to setpublic void setPageMargin (int marginPixels)Set the margin between pages.ParametersmarginPixels    Distance between adjacent pages in pixelsSee AlsogetPageMargin()setPageMarginDrawable(Drawable)setPageMarginDrawable(int)public void setPageMarginDrawable (int resId)Set a drawable that will be used to fill the margin between pages.ParametersresId   Resource ID of a drawable to display between pagespublic void setPageMarginDrawable (Drawable d)Set a drawable that will be used to fill the margin between pages.Parametersd   Drawable to display between pagespublic 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. This allows the application to apply custom property transformations to each page, overriding the default sliding look and feel.Note: Prior to Android 3.0 the property animation APIs did not exist. As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.ParametersreverseDrawingOrder true if the supplied PageTransformer requires page views to be drawn from last to first instead of first to last.transformer PageTransformer that will modify each page's animation propertiesProtected Methods

当然有一部分使我们不需要去掌握的,我们需要的只是如何实现一个简单的定时轮播图。
1.首先我们需要在布局文件中写入一个viewPager,作为盛放轮播Imageview的容器。

            "@+id/line"                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginTop="8dp">                .support.v4.view.ViewPager                    android:id="@+id/viewpager"                    android:layout_marginLeft="5dp"                    android:layout_marginRight="5dp"                    android:layout_width="match_parent"                    android:layout_height="200dp"                    android:clickable="true" />            

然后我们要做的是在activity里面定义监听事件。

pageradapter1 = new PagerAdapter() {            @Override            public int getCount() {                return MAX_VALUE;            }            @Override            public boolean isViewFromObject(View arg0, Object arg1) {                return arg0 == arg1;            }            @Override            public void destroyItem(View container, int position, Object object) {                ((ViewPager) container).removeView(mImageViews1.get(position % mImageViews1.size()));            }            /**             * 载入图片进去,用当前的position 除以 图片数组长度取余数是关键             */            @Override            public Object instantiateItem(View container, int position) {                mImageViews1.get(position % mImageViews1.size()).setBackgroundResource(imgIdArray1[position % mImageViews1.size()]);                ((ViewPager) container).addView(mImageViews1.get(position % mImageViews1.size()), 0);                return mImageViews1.get(position % mImageViews1.size());            }        };

上述代码实现了无限轮播,怎么实现定时无限轮播呢,我们不用着急。

scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();        //每隔4秒钟切换一张图片        scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 8, 4, TimeUnit.SECONDS);//viewPagerTask用来开启新线程并将刷新UI的工作交给主线程。private class ViewPagerTask implements Runnable {        @Override        public void run() {            Message msg = new Message();            msg.what = 3;            mHandler.sendMessage(msg);        }    }

在handle里面写入:

 default:                    viewPager.setCurrentItem(current);                    viewPager1.setCurrentItem(current);                    current++;                    break;

这样就实现了一个完整的轮播图啦!

附上 该轮播实现的一个app 的地址,欢迎fork ,一起做的更好。

https://github.com/panyunyi97/CUFE_TRIP

更多相关文章

  1. Android绘制圆形图片(五)
  2. Android通过内容提供器获取相册中所有图片
  3. Android(安卓)改变ImageView图片的Bitmap大小
  4. android 多张图片动画方式轮播(转载)
  5. Android(安卓)Fresco图片处理库用法API英文原文文档3(Facebook开
  6. Android(安卓)XMl写入
  7. Android(安卓)读取Assets中图片
  8. android 按比例缩放图片(适屏)
  9. android 文字或者图片生成.pdf文件

随机推荐

  1. 搭建NDK环境,运行samples
  2. android--------自定义控件 之 方法篇
  3. Activity Task & Android(安卓)lauchMode
  4. Android(安卓)资源名获取R文件id
  5. 简单好用的控件源码
  6. android WebView在应用内打开网页的问题
  7. this is my home
  8. ionic 打包报某些jar包重复
  9. Android(安卓)ViewPager+Fragment多层嵌
  10. Android之——退出多个Activity