TextSwitcher继承了ViewSwitcher,因此它具有与ViewSwitcher相同的特征,TextSwitcehr需要设置一个ViewFactory,其中的makeView方法还需返回一个TextView组件。
下面是界面布局XML文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.home.androidapptest.MainActivity"> <!--定义了一个TextSwitcher,并指定了文本切换时的动画效果--> <TextSwitcher android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textSwitcher" android:inAnimation="@android:anim/slide_in_left" android:outAnimation="@android:anim/slide_out_right" android:onClick="next"> </TextSwitcher> </LinearLayout>上面的布局文件中定义了一个TextSwitcher,并指定了文本切换时的动画效果,接下来只要为TextSwitcher设置ViewFacrory。Activity代码如下:
public class MainActivity extends AppCompatActivity { TextSwitcher textSwitcher; String[] strs=new String[]{ "疯狂Java讲义", "疯狂Android讲义", "疯狂ajax讲义", "轻量级Java EE企业应用实战" }; 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 ViewSwitcher.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 ]); } }