让TextView里面的文字逐个显示的动画效果实现(1)

 

 

  最近使用TextView时想要实现里面的文字逐个显示的动画效果,就如同打字一样。

  主要实现思想:新建一个TextView的派生类,先将要逐个显示的字符串保存变量 mOriginalStr 中,然后启动新线程,每隔一段时间使用 Handler 类对象的sendEmptyMessage(int what) 方法发送消息,让 Handler 对象将mOriginal中的字符串逐个添加到TextView中进行显示。

 

  代码实现如下:

 1 /**
 2  * Created by Haoye on 2016/1/15.
 3  */
 4 public class SinglyTextView extends TextView {
 5     private String  mOriginalStr;//------用于保存原始字符串
 6     private long    mDuration = 500;//---默认显示每个字符的时间间隔
 7     private int     mIndex    = 0;//-----记录将要显示的字符的位置
 8     private Handler mHandler;
 9     private final int SHOW_NEXT_CHAR = 1;
10 
11   
12     public SinglyTextView(Context context){
13         super(context);
14 
15         init();
16         start();
17     }
18 
19     public SinglyTextView(Context context, @Nullable AttributeSet attrs){
20         super(context, attrs);
21 
22         init();
23         start();
24     }
25 
26     public SinglyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr){
27         super(context, attrs, defStyleAttr);
28 
29         init();
30         start();
31     }
32 
33     private void init() {
34         mOriginalStr = getText().toString();//---保存字符串
35         this.setText("");//-----先清空
36 
37         mHandler = new Handler(){
38             @SuppressLint("HandlerLeak")
39             public  void handleMessage(Message msg){
40                 if (msg.what == SHOW_NEXT_CHAR && mIndex < mOriginalStr.length()){
41                     SinglyTextView.this.setText(SinglyTextView.this.getText(). toString()
42                                                + mOriginalStr.charAt(mIndex));
43                     mIndex++;
44                 }
45 
46             }
47         };
48     }
49 
50     /**
51      * 设置显示每个字符的时间间隔
52      * @param duration
53      */
54     public void setDuration(long duration) {
55         mDuration = duration;
56     }
57 
58     /**
59      * 启动新线程
60      */
61     private void start() {
62          new Thread(){
63             public void run()
64             {
65                 while (mIndex < mOriginalStr.length())
66                 {
67                     try {
68                         Thread.sleep(mDuration);
69                         mHandler.sendEmptyMessage(SHOW_NEXT_CHAR);
70                     }
71                     catch (Exception ex){
72                         ex.printStackTrace();
73                     }
74 
75                 }
76             }
77         }.start();
78     }
79 
80 }

 

  为何要写三个构造函数这么多?因为在我写了第一个后,在xml文件中运用时出现了这个rendering problem

  如果不重写后两个构造函数,可能有些属性就用不了,于是我就添加了上去了,反正就几行代码。其实在TextView 类中还有一个四个参数的构造函数,不过那个构造函数需要在API 21或以上的版本才能用。

 

  

posted @ 2016-01-16 00:15  (•̀ω•́)y  阅读(2667)  评论(0编辑  收藏  举报