TextSwitcher,一个带有文字切换动画效果的加强版TextView
先上图
直接上代码
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="match_parent"
- android:gravity="center"
- android:layout_height="match_parent">
- <!--inAnimation 进入时的动画-->
- <!--outAnimation 退出时的动画-->
- <TextSwitcher
- android:id="@+id/ts_test"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:inAnimation="@anim/anim_in"
- android:outAnimation="@anim/anim_out"
- />
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="切换下一个"
- android:onClick="next"/>
- </LinearLayout>
具体动画代码 退出
- <set xmlns:android="http://schemas.android.com/apk/res/android">
- <translate
- android:fromXDelta="0"
- android:fromYDelta="0"
- android:toXDelta="0"
- android:toYDelta="-100%"
- android:duration="500"/>
- </set>
具体动画代码 进入
- <set xmlns:android="http://schemas.android.com/apk/res/android">
- <translate
- android:fromXDelta="0"
- android:fromYDelta="100%"
- android:toXDelta="0"
- android:toYDelta="0"
- android:duration="500"/>
- </set>
activity代码
- @BindView(R.id.ts_test)
- TextSwitcher ts_test;
- String[] str={
- "第一个",
- "第二个",
- "第三个",
- "第四个"
- };
- int cur;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_swicher);
- ButterKnife.bind(this);
- ts_test.setFactory(new ViewSwitcher.ViewFactory() {
- @Override
- public View makeView() {
- final TextView tv=new TextView(SwicherTestActivity.this);
- tv.setTextSize(25);
- tv.setTextColor(Color.RED);
- tv.setGravity(Gravity.CENTER);
- //设置点击事件
- tv.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Toast.makeText(SwicherTestActivity.this,cur+tv.getText().toString(),Toast.LENGTH_SHORT).show();
- }
- });
- return tv;
- }
- });
- }
- public void next(View view){
- //切换到下一内容,有动画
- ts_test.setText(str[cur++%str.length]);
- //设置立刻生效当前的内容,没有动画展示.
- // ts_test.setCurrentText(str[cur++%str.length]);
- }