上一篇博客《TextSwitcher实现文字上下翻牌效果》中我们知道了TextSwitcher的大致用法,那现在来看看TextSwitcher内部是如何实现文字交替的。
TextSwitcher 继承自 ViewSwitcher
使用TextSwitcher时,我们通过setFactory先给它设定了一个ViewFactory,这个在ViewSwitcher代码中
/** * Sets the factory used to create the two views between which the * ViewSwitcher will flip. Instead of using a factory, you can call * {@link #addView(android.view.View, int, android.view.ViewGroup.LayoutParams)} * twice. * * @param factory the view factory used to generate the switcher's content */ public void setFactory(ViewFactory factory) { mFactory = factory; obtainView(); obtainView(); }
private View obtainView() { View child = mFactory.makeView(); LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp == null) { lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } addView(child, lp); return child; }它里面调用了Factory接口的方法makeView,用来创建内部视图,也就是,上一篇文章中 setFactory中实现的makeView方法,创建TextView,用来显示文字。
当我们对TextSwitcher使用setText设置文字时,看看TextSwitcher干了什么
/** * Sets the text of the next view and switches to the next view. This can * be used to animate the old text out and animate the next text in. * * @param text the new text to display */ public void setText(CharSequence text) { final TextView t = (TextView) getNextView(); t.setText(text); showNext(); }每次setText,都会去获取一个TextView,那么如果是调用上万次的setText,难道要创建上万个TextView吗,谷歌怎么会这么笨!
看下面。
它通过getNextView来获取一个内部的TextView,getNextView在ViewSwitcher中
/** * Returns the next view to be displayed. * * @return the view that will be displayed after the next views flip. */ public View getNextView() { int which = mWhichChild == 0 ? 1 : 0; return getChildAt(which); }
ViewSwitcher 继承自 ViewAnimator,所以它可以支持动画,我们通过setInAnimation和setOutAnimation进行进和出的动画效果。