Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 中文 API(17):TextSwitcher 文字切換動畫

編輯:Android 開發實例

TextSwitcher 專門用來替「會變動的文字」加上進出動畫,例如輪播標題、即時計數、狀態提示。

類別結構

public class TextSwitcher extends ViewSwitcher

繼承鏈:Object → View → ViewGroup → FrameLayout → ViewAnimator → ViewSwitcher → TextSwitcher

類別說明

它是 ViewSwitcher 的特化版本,只接受 TextView 類型的子檢視。每當你呼叫 setText(),它就會用動畫把舊文字淡出、新文字淡入,切換過程因此變得柔和。若直接呼叫 setCurrentText(),則是硬切、不播放動畫。

建構子

  • public TextSwitcher(Context context):建立空的 TextSwitcher。
  • public TextSwitcher(Context context, AttributeSet attrs):以指定的 Context 與屬性集合建立。

公開方法

  • public void addView(View child, int index, ViewGroup.LayoutParams params):加入子檢視;若 child 不是 TextView 會丟出 IllegalArgumentException。
  • public void setCurrentText(CharSequence text):立即換成新文字,不播放動畫。
  • public void setText(CharSequence text):設定下一個檢視的文字並切換,會播放進出動畫。

程式碼示例

以下摘自官方 APIDemos 的 TextSwitcher 範例,點一次按鈕就讓數字淡入淡出地遞增:

public class TextSwitcher1 extends Activity
        implements ViewSwitcher.ViewFactory, View.OnClickListener {

    private TextSwitcher mSwitcher;
    private int mCounter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text_switcher_1);

        mSwitcher = (TextSwitcher) findViewById(R.id.switcher);
        mSwitcher.setFactory(this);

        Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
        Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
        mSwitcher.setInAnimation(in);
        mSwitcher.setOutAnimation(out);

        Button nextButton = (Button) findViewById(R.id.next);
        nextButton.setOnClickListener(this);

        updateCounter();
    }

    public void onClick(View v) {
        mCounter++;
        updateCounter();
    }

    private void updateCounter() {
        mSwitcher.setText(String.valueOf(mCounter));
    }

    public View makeView() {
        TextView t = new TextView(this);
        t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
        t.setTextSize(36);
        return t;
    }
}

對應的版面配置:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button android:id="@+id/next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next" />

    <TextSwitcher android:id="@+id/switcher"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

使用要點

TextSwitcher 一定要先設定 ViewFactory(實作 makeView() 傳回一個 TextView),否則無法運作;接著用 setInAnimation() 與 setOutAnimation() 指定進出動畫,最後一律透過 setText() 更新內容,動畫才會生效。

資料來源:Android 官方 API 文件與 APIDemos 整理。

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