讓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或以上的版本才能用。

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM