android 开发技巧(5)--使 用 TextSwitcher 实现平滑过渡

来源:互联网 发布:jquery javascript 编辑:程序博客网 时间:2024/05/18 02:35

如果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>
0 0
原创粉丝点击