Android TextSwitcher - 文本切换器

图片的切换可以使用ImageSwitcher来实现,同样文本的切换动画也可以使用Android TextSwitcher类,他们都继承ViewSwitcher类。

ViewSwitcher仅仅包含子类型TextView。TextSwitcher被用来使屏幕上的label产生动画效果。每当setText(CharSequence)被调用时,TextSwitcher使用动画方式将当前的文字内容消失并显示新的文字内容。

package com.android.study; 
  
import java.util.Timer; 
import java.util.TimerTask; 
  
import android.app.Activity; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.animation.AnimationUtils; 
import android.widget.Button; 
import android.widget.TextSwitcher; 
import android.widget.TextView; 
import android.widget.ViewSwitcher.ViewFactory; 
  
public class TextSwitcherActivity extends Activity implements ViewFactory { 
    /** Called when the activity is first created. */
    TextSwitcher switcher; 
    Handler handler; 
    String[] resources = { " ", "身是菩提树,", "心如明镜台,", "时时勤拂拭,", "勿使惹尘埃。" }; 
    private Handler mHandler = new Handler() { 
  
        public void handleMessage(Message msg) { 
            switch (msg.what) { 
            case 1: 
                id = next(); // 更新Id值 
                updateText(); // 更新TextSwitcherd显示内容; 
                break; 
            } 
        }; 
    }; 
    int id = 0; // resources 数组的Id; 
  
    @Override
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        init(); 
        Timer timer = new Timer(); 
        timer.scheduleAtFixedRate(new MyTask(), 1, 3000);// 每3秒更新 
    } 
  
    private void init() { 
        switcher = (TextSwitcher) findViewById(R.id.switcher); 
        switcher.setFactory(this); 
        switcher.setInAnimation(AnimationUtils.loadAnimation(this, 
                android.R.anim.fade_in)); 
        switcher.setOutAnimation(AnimationUtils.loadAnimation(this, 
                android.R.anim.fade_out)); 
    } 
  
    private int next() { 
  
        int flag = id + 1; 
        if (flag > resources.length - 1) { 
            flag = flag - resources.length; 
        } 
        return flag; 
    } 
  
    private void updateText() { 
        switcher.setText(resources[id]); 
    } 
  
    @Override
    public View makeView() { 
        // TODO Auto-generated method stub 
        TextView tv = new TextView(this); 
        tv.setText(resources[id]); 
        return tv; 
    } 
  
    private class MyTask extends TimerTask { 
        @Override
        public void run() { 
            Message message = new Message(); 
            message.what = 1; 
            mHandler.sendMessage(message); 
  
        } 
    } 
}

Android-TextSwitcher



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值