2016年12月9日 星期五

TabLayout頁面切換教學(Part1)


前言:TabLayout是在於App中頂部屬於AppBar的一環,此教學會使用 ViewPager,搭配一個元件叫做 TabLayout,來實作頁籤的點擊與左右滑動切換,其中每個頁籤都代表一個 Fragment下面是官方對於Fragment的說明網頁
https://developer.android.com/guide/components/fragments.html


由圖得知上面的標籤是由TabLayout來實作而下面的內容變換則是ViewPager以及Fragment實作的

加入design資源再Sync同步

1.我們從Toolbar開始,先在build.gradle的dependencies大括號裡面加入
   後面的24.2.1版本對應您的appcompat-v7才能正確的被執行哦!

compile 'com.android.support:design:24.2.1'

●styles.xml更改無ActionBar
























建立自定義Toolbar


新增一個XML檔

File name= app_bar
Root element=android.support.v7.Toolbar
<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:minHeight="?attr/actionBarSize"

    android:fitsSystemWindows="true"

    android:background="@color/colorPrimary"

    app:theme="@style/Base.ThemeOverlay.AppCompat.Dark"

    >



</android.support.v7.widget.Toolbar>



activity_main.xml


1.先建立android.support.design.widget.AppBarLayout 再把剛剛所建立的app_bar.xml <include>進去,再來再新增android.support.design.widget.TabLayout 也就是左右滑動的選單
最後再建立ViewPager
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:id="@+id/activity_main"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="com.example.andy6804tw.tabbed.MainActivity">

    <android.support.design.widget.AppBarLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:theme="@style/Base.ThemeOverlay.AppCompat.Dark">

        <include

            android:layout_height="wrap_content"

            android:layout_width="match_parent"

            layout="@layout/app_bar"

            android:id="@+id/app_bar"/>

        <android.support.design.widget.TabLayout

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:id="@+id/tabLayout"

            app:tabGravity="fill"

            app:tabMode="fixed">

        </android.support.design.widget.TabLayout>



    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:id="@+id/viewPager">

    </android.support.v4.view.ViewPager>



</RelativeLayout>

沒有留言:

張貼留言