文本切换器(TextSwitcher)的功能与用法

TextSwitcher集成了ViewSwitcher, 因此它具有与ViewSwitcher相同的特性:可以在切换View组件时使用动画效果。与ImageSwitcher相似的是,使用TextSwitcher也需要设置一个ViewFactory。与ImageSwitcher不同的是,TextSwitcher所需要的ViewFactory的makeView()方法必须返回一个TextView组件。

<TextSwitcher与TextView的功能有点类似,它们都可用于显示文本内容,区别在于TextSwitcher的效果更炫,它可以指定文本切换时的动画效果。> 

不多说,直接上代码了。界面布局文件如下:

 

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" >  
  5.       
  6.     <!-- 定义一个TextSwitcher,并制定了文本切换时的动画效果 -->  
  7.   
  8.     <TextSwitcher  
  9.         android:id="@+id/textSwitcher"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:textAlignment="center"  
  13.         android:layout_centerHorizontal="true"  
  14.         android:layout_centerVertical="true"  
  15.         android:inAnimation="@android:anim/slide_in_left"  
  16.         android:outAnimation="@android:anim/slide_out_right"   
  17.         android:onClick="next"  
  18.         >  
  19.     </TextSwitcher>  
  20.   
  21. </RelativeLayout>  

上面的布局文件中定义了一个TextSwitcher,并为该文本切换指定了文本切换时的动画效果,接下来Activity只要为该TextSwitcher设置ViewFactory,该TextSwitcher即可正常工作。

 

如下是Activity代码:

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * TextSwitcher practice. 
  3.  * @author peter. 
  4.  * 
  5.  */  
  6. public class MainActivity extends Activity {  
  7.   
  8.     private TextSwitcher textSwitcher;  
  9.       
  10.     // 要显示的文本  
  11.     String[] strs = new String[]  
  12.             {  
  13.              "one",  
  14.              "two",  
  15.              "three"  
  16.              };  
  17.     private int curStr;  
  18.       
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.activity_main);  
  23.         textSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher);  
  24.         textSwitcher.setFactory(new ViewFactory() {  
  25.               
  26.             @Override  
  27.             public View makeView() {  
  28.                 TextView tv = new TextView(MainActivity.this);  
  29.                 tv.setTextSize(40);  
  30.                 // 字体颜色品红  
  31.                 tv.setTextColor(Color.MAGENTA);  
  32.                 return tv;  
  33.             }  
  34.         });  
  35.         //调用next方法显示下一个字符串  
  36.         next(null);  
  37.     }  
  38.       
  39.     // 事件处理函数,控制显示下一个字符串  
  40.     public void next(View source) {  
  41.         textSwitcher.setText(strs[curStr++ % strs.length]);  
  42.     }  
  43.   
  44. }  
posted @ 2016-11-28 15:38  天涯海角路  阅读(128)  评论(0)    收藏  举报