- 我对这三个组件的理解我对这三个组件的理解
最终要实现的效果是可以通过屏幕的左右滑动,切换导航栏,同时也能点击导航栏切换不同的页面。截图:
我的理解:Tablayout组件就是顶部导航栏的部分,ViewPager是页面中除了导航栏以外的部分,即展示内容的部分,而Fragment(碎片)就是来处理这部分数据填充的工具,换言之就是用fragment来设置每个标签下显示的内容是什么。
- 实现过程
- 看一下文件目录吧:主要包含的文件就是三个java类和两个.xml文件
1.添加依赖库
因为要使用这个TabLayout,需要在build.gradle文件的dependencies中加入compile 'com.android.support:design:27.1.1’这一行。这个版本号根据你的版本号来定,也可以在build.gradle文件中看到你的sdk版本号,比如我的就是:
2.创建main_activity.xml文件
这个文件中主要就是包含两个组件:viewPager和Tablayout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="true"
android:fitsSystemWindows="true"
android:orientation="vertical"
tools:context="com.example.lenovo.learningandroid.MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorAccent" />
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
3.创建fragment_detail_info.xml
这个布局文件用于显示除了导航栏以外下面的内容,这里只写了一个Textview,可以根据需要来增加组件
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools