TextSwitcher集成了ViewSwitcher, 因此它具有与ViewSwitcher相同的特性:可以在切换View组件时使用动画效果。与ImageSwitcher相似的是,使用TextSwitcher也需要设置一个ViewFactory。与ImageSwitcher不同的是,TextSwitcher所需要的ViewFactory的makeView()方法必须返回一个TextView组件。
<TextSwitcher与TextView的功能有点类似,它们都可用于显示文本内容,区别在于TextSwitcher的效果更炫,它可以指定文本切换时的动画效果。>
不多说,直接上代码了。界面布局文件如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- 定义一个TextSwitcher,并制定了文本切换时的动画效果 -->
<TextSwitcher
android:id="@+id/textSwitcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:inAnimation="@android:anim/slide_in_left"
android:outAnimation="@android:anim/slide_out_right"
android:onClick="next"
>
</TextSwitcher>
</RelativeLayout>
上面的布局文件中定义了一个TextSwitcher,并为该文本切换指定了文本切换时的动画效果,接下来Activity只要为该TextSwitcher设置ViewFactory,该TextSwitcher即可正常工作。
如下是Activity代码:
/**
* TextSwitcher practice.
* @author peter.
*
*/
public class MainActivity extends Activity {
private TextSwitcher textSwitcher;
// 要显示的文本
String[] strs = new String[]
{
"one",
"two",
"three"
};
private int curStr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher);
textSwitcher.setFactory(new ViewFactory() {
@Override
public View makeView() {
TextView tv = new TextView(MainActivity.this);
tv.setTextSize(40);
// 字体颜色品红
tv.setTextColor(Color.MAGENTA);
return tv;
}
});
//调用next方法显示下一个字符串
next(null);
}
// 事件处理函数,控制显示下一个字符串
public void next(View source) {
textSwitcher.setText(strs[curStr++ % strs.length]);
}
}