如果TextView需要循环切换内容,使用setText()会立刻改变,没有动画。为了使过渡过程的视觉效果更自然,Android 提供了 TextSwitcher 和 ImageSwitcher 这两个类分别替代TextView 与 ImageView。TextSwitcher 用于为文本标签添加动画功能
使用步骤
1) 通 过 findViewById() 方 法 获 取 TextSwitcher 对 象 的 引 用
switcher,当然也可以直接在代码中构造该对象。
2) 通 过 switcher.setFactory() 方 法 指 定 TextSwitcher 的 ViewFactory。
3)通过 switcher.setInAnimation() 方法设置换入动画效果。
4)通过 switcher.setOutAnimation() 方法设置换出动画效果。

TextSwitcher 的工作原理
首先通过 ViewFactory 创建两个用于在 TextSwitcher 中切换的视图,每当调用 setText() 方法时,TextSwitcher 首先移除当前视图并显示 setOutAnimation() 方法设置的动画,然后并将另一个视图切换进来,并显示 setInAnimation()方法设置的动画

效果图

代码

public class Hack05Activity extends AppCompatActivity {    private static final String[] TEXTS = { "First", "Second", "Third" };    private int mTextsPosition = 0;    private TextSwitcher mTextSwitcher;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_hack05);        mTextSwitcher = (TextSwitcher) findViewById(R.id.your_textview);        mTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() {            @Override            public View makeView() {                TextView t = new TextView(Hack05Activity.this);                t.setGravity(Gravity.CENTER);                return t;            }        });        mTextSwitcher.setInAnimation(this, android.R.anim.fade_in);        mTextSwitcher.setOutAnimation(this, android.R.anim.fade_out);        onSwitchText(null);    }    public void onSwitchText(View v) {        mTextSwitcher.setText(TEXTS[mTextsPosition]);        setNextPosition();    }    private void setNextPosition() {        mTextsPosition = (mTextsPosition + 1) % TEXTS.length;    }}

布局xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" >    <TextSwitcher  android:id="@+id/your_textview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" />    <Button  android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:onClick="onSwitchText" android:text="Click me" /></RelativeLayout>

更多相关文章

  1. ListView的item点击事件及item中子view的点击事件冲突处理方法和
  2. Android开机画面
  3. Android学习之Adapter(适配器)源代码分析与观察者模式的运用(一)
  4. Android(安卓)在oncreate() 方法中调用 findViewById 返回 null
  5. Android简明开发教程十八:自定义对话框 Transform
  6. Android中的序列化和反序列化
  7. Android(安卓)Studio 开发基础经验汇总
  8. android Activity设置透明主题样式方法
  9. Android加速启动Activity

随机推荐

  1. MySQL事务的基础学习以及心得分享
  2. 详解MySQL分组链接的使用技巧
  3. win10下完全卸载+重装MySQL步骤详解
  4. MySQL数据库Event定时执行任务详解
  5. MYSQL如何自动为查询数据的结果编上序号
  6. 一条sql语句完成MySQL去重留一
  7. Mysql 8 新特性 window functions 的作用
  8. mysql5.7安装及配置教程
  9. 实例测试MySQL的enum类型
  10. MySQL 5.7.20绿色版安装详细图文教程