[Android] TextSwitcher,textswitcher
在上文當中,我們描述了如何使用TextSwitcher控制項。本文將通過分析Android Framework層源碼來闡釋它是如何?文本的平滑切換的的。
TextSwitcher的類繼承關係
有此繼承結構我們可以知道,TextSwitcher:
- 繼承自FrameLayout,所以其子View層疊地放置著
- 繼承自ViewAnimator,所以其持有兩個Animation對象,用於呈現淡出、漸入等動畫效果。
setFactory做了什麼
閱讀ViewSwitcher源碼,我們可以發現在setFactory方法中,會構造2個我們在makeView回調中產生的視圖。
public void setFactory(ViewFactory factory) { mFactory = factory; // 構建一個子View obtainView(); // 再構建一個子View obtainView(); }
然後,又將這2個View對象加入到了FrameLayout中。
setInAnimation和
setOutAnimation做了什麼
就是設定ViewAnimator所持有的Animation對象。
android.view.animation.Animation
public void setInAnimation(Animation inAnimation) { mInAnimation = inAnimation; }
setText做了什麼
public void setText(CharSequence text) { final TextView t = (TextView) getNextView(); t.setText(text); // 顯示下一個View showNext(); }
最終調用了android.widget.ViewAnimator的showOnly方法。
void showOnly(int childIndex, boolean animate) { final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (i == childIndex) { if (animate && mInAnimation != null) { // 讓新TextView示範進入動畫 child.startAnimation(mInAnimation); } child.setVisibility(View.VISIBLE); mFirstTime = false; } else { if (animate && mOutAnimation != null && child.getVisibility() == View.VISIBLE) { // 讓舊TextView示範淡齣動畫 child.startAnimation(mOutAnimation); } else if (child.getAnimation() == mInAnimation) child.clearAnimation(); child.setVisibility(View.GONE); } } }
從而實現了文本視圖的平滑切換。
註:
1. 相關代碼在 GitHub
2. 配套視頻在 優酷