Android單行跑馬燈效果實現


參考網址:https://www.jianshu.com/p/e6c1b825d322

起初,使用了如下XML布局:

 1 <TextView
 2                 android:id="@+id/tv_person_name"
 3                 android:layout_marginTop="16dp"
 4                 android:layout_width="125dp"
 5                 android:layout_height="wrap_content"
 6                 android:text="健康快樂的小..."
 7                 android:textSize="20sp"
 8                 android:textColor="#CE000000"
 9                 android:layout_alignParentLeft="true"
10                 android:layout_marginLeft="85dp"
11                 android:singleLine="true"//設置單行
12                 android:ellipsize="marquee"//跑馬燈
13                 android:marqueeRepeatLimit="marquee_forever"//無限循環
14                 android:focusable="true"//獲得焦點
15                 android:focusableInTouchMode="true" />

結果是:能暫時實現跑馬燈效果,但在多次點擊事件之后容易失焦。而且在Android4.4上實現有短暫停頓。

focusable和focusableInTouchMode的區別:https://blog.csdn.net/SylG17/article/details/85047234

曾嘗試通過EvenBus重新獲取焦點,但是並無卵用。

后來采用自定義跑馬燈類:

 1 public class MarqueeTextView extends AppCompatTextView {
 2     /** 滾動次數 */
 3     private int marqueeNum = -1;//-1為永久循環,大於0是循環次數。`
 4     public void setMarqueeNum(int marqueeNum) {
 5         this.marqueeNum = marqueeNum;
 6     }
 7     public MarqueeTextView(Context context) {
 8         super(context);
 9         setAttr();
10     }
11     public MarqueeTextView(Context context, AttributeSet attrs) {
12         super(context, attrs);
13         setAttr();
14     }
15     public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
16         super(context, attrs, defStyle);
17         setAttr();
18     }
19     /**
20      * 始終獲取焦點
21      * 跑馬燈在TextView處於焦點狀態的時候才會滾動
22      */
23     @Override
24     public boolean isFocused() {
25         return true;
26     }
27     /**
28      * 設置相關屬性
29      */
30     private void setAttr(){
31         this.setEllipsize(TextUtils.TruncateAt.MARQUEE);//設置跑馬等效果
32         this.setMarqueeRepeatLimit(marqueeNum);//設置跑馬燈重復次數
33         this.setSingleLine(true);//設置單行
34     }
35 }

采用自定義跑馬燈控件:

 1 <com.sz.cszj.intelligentrobot.cszjrobot.view.MarqueeTextView
 2                 android:id="@+id/tv_person_name"
 3                 android:layout_marginTop="16dp"
 4                 android:layout_width="125dp"
 5                 android:layout_height="wrap_content"
 6                 android:text="健康快樂的小..."
 7                 android:textSize="20sp"
 8                 android:textColor="#CE000000"
 9                 android:layout_alignParentLeft="true"
10                 android:layout_marginLeft="85dp"/>

效果:不會失焦,能實現跑馬燈效果。但是依然會有卡頓。


免責聲明!

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



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