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

TextSwitcher 是什麼?三步實現文本淡入淡出切換

編輯:關於 Android 程式設計

TextSwitcher 的 Java Doc 是這樣自我介紹的:

Specialized ViewSwitcher that contains only children of type TextView. A TextSwitcher is useful to animate a label on screen. Whenever setText(CharSequence) is called, TextSwitcher animates the current text out and animates the new text in.

翻譯過來就是兩件事:它是一個只容納 TextView 子視圖的 ViewSwitcher;每次調用 setText 時,舊文本退場動畫與新文本進場動畫同時播放,形成平滑切換的視覺效果。

三步接入

第一步,在佈局裡加入控件:

<TextSwitcher
    android:id="@+id/ts"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_marginTop="20dp"
    android:layout_weight="1" />

第二步,設置工廠。TextSwitcher 自己不會造子視圖,必須由 ViewFactory 提供:

mTs.setFactory(new TextSwitcher.ViewFactory() {
    @Override
    public View makeView() {
        return LayoutInflater.from(getApplicationContext())
                .inflate(R.layout.text, null);
    }
});

注意 R.layout.text 的根節點必須是 TextView(或它的子類),否則後續的強制轉型會出問題。

第三步,設置進出動畫:

mTs.setInAnimation(AnimationUtils.loadAnimation(
        getApplicationContext(), android.R.anim.fade_in));
mTs.setOutAnimation(AnimationUtils.loadAnimation(
        getApplicationContext(), android.R.anim.fade_out));

之後調用 mTs.setText(txt),效果如下:

三處細節值得留意:setFactory 必須在 setText 之前調用,否則沒有子視圖可用;動畫也可以直接用 XML 定義後傳入,能實現自訂的位移、透明度曲線;由於內部只維持兩個 TextView 並反覆複用,頻繁刷新文本不會造成對象爆炸,非常適合做輪播標題、播放提示這類場景。

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