当前位置: 代码迷 >> Android >> [Android] TextSwitcher - 如何做到的
  详细解决方案

[Android] TextSwitcher - 如何做到的

热度:75   发布时间:2016-04-28 01:34:35.0
[Android] TextSwitcher -- 怎么做到的

在上文当中,我们描述了如何使用TextSwitcher控件。本文将通过分析Android Framework层源码来阐释它是如何实现文本的平滑切换的的。

TextSwitcher的类继承关系

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中。

setInAnimationsetOutAnimation做了什么

就是设置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.ViewAnimatorshowOnly方法。

    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. 配套视频在 [优酷] (http://v.youku.com/v_show/id_XOTMyMjIxNzE2.html)

  相关解决方案