通过TextSwitcher实现广告栏内容动画切换

本文介绍如何在Android应用中使用TextSwitcher组件实现文本的动画切换效果。通过设置不同的进入和退出动画,可以创建丰富的视觉体验。代码示例展示了如何通过Handler定时更新TextSwitcher的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

textswitcher
1,布局中使用

  <TextSwitcher
        android:id="@+id/switcher"
        android:layout_width="match_parent"
        //控制进入动画  根据需求自顶更改
        android:inAnimation="@anim/enter_animation"
        //控制退出的动画
        android:outAnimation="@anim/outer_animation"
        android:background="@color/cardview_dark_background"
        android:layout_height="wrap_content">
    </TextSwitcher>

//动画 enter_animation

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="2000"
        android:fromYDelta="100%p"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toYDelta="0%p" />
</set>

//退出动画 outer_animation

public class MainActivity extends FragmentActivity {
    int index;
    String  [] str={"fahkfahkfha","窗前明月光"};
    private Handler mHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            index++;
            mTextSwitcher.setText(str[index%2]);
            mHandler.sendEmptyMessageDelayed(0,2000);
        }
    };
    private TextSwitcher mTextSwitcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextSwitcher = (TextSwitcher) findViewById(R.id.switcher);
        mTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                TextView  textView=new TextView(MainActivity.this);
                FrameLayout.LayoutParams layoutParams=   new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                textView.setPadding(0,40,0,40);
                textView.setGravity(Gravity.CENTER_HORIZONTAL);
                textView.setLayoutParams(layoutParams);
                return textView;
            }
        });
        mTextSwitcher.setText("hahahha");
        mHandler.sendEmptyMessageDelayed(0,2000);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值