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

TextSwitcher继承了ViewSwitcher,因此它具有与ViewSwitcher相同的特征:可以在切换View组件时使用动画效果。与ImageSwitcher相似的是,使用TextSwitcher也需要设置一个ViewFactory。与ImageSwitcher不同的是,TextSwitcher所需的ViewFactory的makeView()方法必须返回一个TextView组件。TextSwitcher与TextView的功能有点相似,它们都可用于显示文本内容,区别在于TextSwitcher的效果更炫,它可以指定文本切换时的动画效果。

下面是布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--定义一个TextSwitcher,并指定了文本切换时的动画效果-->
<TextSwitcher
    android:id="@+id/textSwitcher"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inAnimation="@android:anim/slide_in_left"
    android:outAnimation="@android:anim/slide_out_right"
    android:onClick="next"/>
</LinearLayout>

下面是Activity代码

public class MainActivity extends AppCompatActivity {

    private TextSwitcher textSwitcher;
    private String[] strings = new String[]{"人生得意须尽欢", "莫使金樽空对月", "天生我材必有用", "千金散尽还复来"};
    private int curStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textSwitcher = findViewById(R.id.textSwitcher);
        textSwitcher.setFactory(() -> {
            TextView textView = new TextView(MainActivity.this);
            textView.setTextSize(40f);
            textView.setTextColor(Color.MAGENTA);
            return textView;
        });
        //调用next方法显示下一个字符串
        next(null);
    }
    //事件处理函数,控制显示下一个字符串
    public void next(View source) {
        textSwitcher.setText(strings[curStr++ % strings.length]);
    }
}

 

 

原文地址:https://www.cnblogs.com/de1021/p/11837570.html