In the above, we describe how to use the textswitcher control. This article will analyze the Android framework layer source code to illustrate how it achieves smooth text switching.
Class inheritance relationship of Textswitcher
With this inheritance structure we can know that Textswitcher:
-Inherits from Framelayout, so its sub-view is stacked to place
-Inherits from Viewanimator, so it holds two Animation objects, which are used to render fade-out, fade-in, and other animated effects.
setFactoryWhat did it do?
Reading the viewswitcher source code, we can see that in the setFactory method, we construct 2 views that we generated in the makeView callback.
publicvoidsetFactory(ViewFactory factory) { mFactory = factory; // 构建一个子View obtainView(); // 再构建一个子View obtainView(); }
The 2 view objects are then added to the framelayout .
setInAnimationAndsetOutAnimationWhat did it do?
is to set the Animation object held by the Viewanimator .
android.view.animation.Animation
publicvoidsetInAnimation(Animation inAnimation) { mInAnimation = inAnimation; }
setTextWhat did it do?
publicvoidsetText(CharSequence text) { final TextView t = (TextView) getNextView(); t.setText(text); // 显示下一个View showNext(); }
android.widget.ViewAnimatorthe method that was finally called showOnly .
voidShowonly (intChildindex,BooleanAnimate) {Final intCount = Getchildcount (); for(inti =0; I < count; i++) {FinalView child = Getchildat (i);if(i = = Childindex) {if(Animate && minanimation! =NULL) {//Let the new TextView demo Enter the animationChild.startanimation (minanimation); } child.setvisibility (view.visible); Mfirsttime =false; }Else{if(Animate && moutanimation! =NULL&& child.getvisibility () = = view.visible) {//Let old TextView demo fade out animationsChild.startanimation (moutanimation); }Else if(child.getanimation () = = Minanimation) child.clearanimation (); Child.setvisibility (View.gone); } } }
This enables smooth switching of text views.
Note:
1. Related Code on GitHub
2. Supporting video in [Youku] ()
[Android] Textswitcher--How do you do that?