1、创建碎片Fragment对应的类和布局文件,以及加载数据的适配器类。如下图所示的目录。
2、一吨易坌荐切文件构建完毕之后,首先对布局文件进行设计。可以通过拖动控件实现,也可以用代码实现。下面是activity_main.xml文件的效果图和代码鲇馔仓扔截图。这里的ViewPager的作用就是提供用户实现左右翻页滑动切换数据的容器。原文注释:Layout manager that allows the user to flip left and right through pages of data.You supply an implementation of aPagerAdapterto generate the pages that the view shows.除此之外还要顾及到他的兼容性。
3、接下来是要切换的三个界面的布局,就是简单地拖了个控件来区别他们的不同。
4、正如以前往listview中添加数据一样,这里的ViewPager也需要一个适配器的类,它继承的是僻棍募暖FragmentPagerAdapter。下图是实现的代码。这只是代码的主体,如果不导入相应的包可能出错误。
5、接下来让我们实现三个碎片的类。几乎一样。都是妤伊佛集继承父类Fragment,然后重写其中的onCreateView方法。该方法的几个参数说明依次是:inflaterThe LayoutInflater object that can be used to inflate any views in the fragment,containerIf non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view.savedInstanceStateIf non-null, this fragment is being re-constructed from a previous saved state as given here.ReturnsReturn the View for the fragment's UI, or null.
6、接下来是MainActivity中代码的编写。该文件是程序的主界面的实现
7、ok,万事俱备了,启动程序,看看效果吧,这是最后的运行效果。运行后左右滑动就可以在同一个activity中切换界面了。