Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

TabHost 搭配 Fragment 實作帶轉場動畫的分頁切換

編輯:關於 Android 程式設計

TabHost 是舊式但至今仍在維護中的分頁元件。它最大的短板是切頁時畫面硬切,沒有過渡。只要繼承 TabHost 並改寫 setCurrentTab,就能加入「舊頁滑出、新頁滑入」的效果。

先想清楚動畫的兩半

一次切換其實包含兩個獨立動作:離開的那一頁要往某個方向滑出,進入的那一頁要從反方向滑進來。這兩段動畫必須分開設定,且都以「相對自身」與「相對父容器」兩種座標系分別描述,否則會出現頁面一起飄走的怪異情形。

自訂 BoardTabHost

import android.content.Context;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.TabHost;

public class BoardTabHost extends TabHost {
    private int currentTab = 0;
    int duration = 1000;// ms,數值越大越慢

    public BoardTabHost(Context context) {
        super(context);
    }

    public BoardTabHost(Context context, AttributeSet attr) {
        super(context, attr);
    }

    @Override
    public void setCurrentTab(int index) {
        // 切換需要兩段動畫:先把目前頁滑出,再讓目標頁滑入
        if (index > currentTab) {
            // 往右翻頁:目前頁由右向左離開
            TranslateAnimation translateAnimation = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, -1.0f,
                    Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f);
            translateAnimation.setDuration(duration);
            getCurrentView().startAnimation(translateAnimation);
        } else if (index < currentTab) {
            // 往左翻頁:目前頁由左向右離開
            TranslateAnimation translateAnimation = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 1.0f,
                    Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f);
            translateAnimation.setDuration(duration);
            getCurrentView().startAnimation(translateAnimation);
        }

        super.setCurrentTab(index);// 此時 currentTab 已更新

        if (index > currentTab) {
            TranslateAnimation translateAnimation = new TranslateAnimation(
                    Animation.RELATIVE_TO_PARENT, 1.0f, // 從畫面右側外飛入
                    Animation.RELATIVE_TO_PARENT, 0f,   // 停在原位
                    Animation.RELATIVE_TO_PARENT, 0f,
                    Animation.RELATIVE_TO_PARENT, 0f);
            translateAnimation.setDuration(duration);
            getCurrentView().startAnimation(translateAnimation);
        } else if (index < currentTab) {
            TranslateAnimation translateAnimation = new TranslateAnimation(
                    Animation.RELATIVE_TO_PARENT, -1.0f,
                    Animation.RELATIVE_TO_PARENT, 0f,
                    Animation.RELATIVE_TO_PARENT, 0f,
                    Animation.RELATIVE_TO_PARENT, 0f);
            translateAnimation.setDuration(duration);
            getCurrentView().startAnimation(translateAnimation);
        }
        currentTab = index;
    }
}

版面檔 activity_board.xml

頂端放 TabWidget 負責標籤,下方 FrameLayout 負責容納 Fragment:

<?xml version="1.0" encoding="utf-8"?>
<com.rust.tabhostdemo.BoardTabHost
    android:id="@android:id/tabhost"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.rust.tabhostdemo.BoardActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <fragment
                android:id="@+id/fragment_tab1"
                android:name="com.rust.tabhostdemo.TabFragment1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
            <fragment
                android:id="@+id/fragment_tab2"
                android:name="com.rust.tabhostdemo.TabFragment2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
            <fragment
                android:id="@+id/fragment_tab3"
                android:name="com.rust.tabhostdemo.TabFragment3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
        </FrameLayout>
    </LinearLayout>
</com.rust.tabhostdemo.BoardTabHost>

這裡有個容易踩到的地雷:三個 id 必須沿用 android 命名空間下的內建值,也就是 @android:id/tabhost、@android:id/tabs、@android:id/tabcontent。自行命名會讓 TabHost 找不到對應的檢視而直接拋出例外。

Activity 中掛上三個分頁

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

public class BoardActivity extends FragmentActivity {
    public static final String TAB1 = "tab1";
    public static final String TAB2 = "tab2";
    public static final String TAB3 = "tab3";
    public static BoardTabHost boardTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_board);
        boardTabHost = (BoardTabHost) findViewById(android.R.id.tabhost);
        boardTabHost.setup();
        boardTabHost.addTab(boardTabHost.newTabSpec(TAB1)
                .setIndicator(getString(R.string.tab1_name))
                .setContent(R.id.fragment_tab1));
        boardTabHost.addTab(boardTabHost.newTabSpec(TAB2)
                .setIndicator(getString(R.string.tab2_name))
                .setContent(R.id.fragment_tab2));
        boardTabHost.addTab(boardTabHost.newTabSpec(TAB3)
                .setIndicator(getString(R.string.tab3_name))
                .setContent(R.id.fragment_tab3));
        boardTabHost.setCurrentTab(0);
    }
}

檔案結構

── layout

├── activity_board.xml
├── fragment_tab1.xml
├── fragment_tab2.xml
└── fragment_tab3.xml

── tabhostdemo

├── BoardActivity.java
├── BoardTabHost.java
├── TabFragment1.java
├── TabFragment2.java
└── TabFragment3.java

要留意 setCurrentTab 內的 currentTab 是在呼叫 super 之後才更新,因此第二次的 if 判斷用的是舊值,這正是能正確分辨方向的原因,改寫時別把順序調動。若專案已採用 AndroidX,TabHost 仍可使用,但更建議改用 ViewPager2 搭配 TabLayout,能免費取得滑動手勢與更完整的轉場控制。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved