项目中遇到一个需求:ViewPager 一屏显示多个子页面。由于以前没有作过这样的界面,因此经历了些许小插曲,特以记之!android
主要内容来自: http://blog.csdn.net/JM_beizi/article/details/51297605git
经过查询资料,发现有两种解决方案:github
PagerAdapter.getPageWidth(int position)
方法android:clipChildren="false"
这个属性PagerAdapter相关源码:缓存
/** * Returns the proportional width of a given page as a percentage of the * ViewPager's measured width from (0.f-1.f] * * @param position The position of the page requested * @return Proportional width for the given page position */ public float getPageWidth(int position) { return 1.f; }
配置 ViewPager 和其父布局的 android:clipChildren
属性为 false布局
android:clipChildren
表示是否限制子 View 在其范围内,默认为 true。.net
代码中经过 setClipChildren(false)
方法设置。code
特别注意:xml
setClipChildren(false)
在 3.0 以上版本中,开启了硬件加速后将不能正常工做,因此须要将其设置为软件加速。设置软硬件加速使用setLayerType(View.LAYER_TYPE_SOFTWARE, null)
; 也能够在布局文件中添加android:layerType="software"
- 经过设置 ViewPager 的
layout_marginLeft
和layout_marginLeft
两个属性,能够设置其余页面(非当前页面)的显示大小
<RelativeLayout android:id="@+id/viewPager_container" android:layout_width="match_parent" android:layout_height="200dp" android:background="@android:color/white" android:clipChildren="false" android:layerType="software"> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="110dp" android:layout_marginRight="110dp" android:clipChildren="false" /> </RelativeLayout>
mViewPager.setOffscreenPageLimit(2); // 2 表示除了当前页面,再缓存其余两个页面
mViewPager.setPageMargin(int marginPixls); // setPageMargin表示设置page之间的间距
blog
以下事项来自参考文章的评论区:事件
使用过程当中,第二个问题未重现!
此文在个人 Github Pages 上同步发布,地址为:{{ title }}