網上有很多跑馬燈的介紹,有很多跑馬燈的代碼。或許我的不是最好的,但是應該很容易明白的。
我們先來介紹一個跑馬燈的代碼
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:layout_width="match_parent" 3 android:layout_height="match_parent" 4 android:orientation="vertical"> 5 6 <TextView 7 android:id="@+id/wisdom_tv" 8 android:layout_width="wrap_content" 9 android:layout_height="wrap_content" 10 android:text="你必須非常努力,才能看起來毫不費勁!-Moon同學的勵志語言" 11 android:textSize="24sp" 12 android:singleLine="true" 13 android:ellipsize="marquee" 14 android:focusableInTouchMode="true" 15 android:focusable="true"/> 16 17 <!-- 18 android:ellipsize="start" 省略號在開頭 19 android:ellipsize="middle" 省略號在中間 20 android:ellipsize="end" 省略號在結尾 21 android:ellipsize="marquee" 跑馬燈顯示 22 --> 23 <!-- 24 android:singleLine="true" 內容只能顯示在一行 25 android:focusableInTouchMode="true" 通過touch來獲得focus 26 android:focusable="true" 是否可以獲取焦點 27 --> 28 </LinearLayout>
當然如果是一個跑馬燈的話,那么這個就完全可以了,但是在以后的開發中,布局會很復雜的,如果出現兩個以上的跑馬燈的話,那么重復上面的代碼,那么是實現不了的,那么兩個以上的應該要怎么做呢?
layout布局的代碼如下
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <com.shxt.xkl.MaequeeText 8 android:layout_width="wrap_content" 9 android:layout_height="wrap_content" 10 android:ellipsize="marquee" 11 android:focusable="true" 12 android:focusableInTouchMode="true" 13 android:singleLine="true" 14 android:text="你必須非常努力,才能看起來毫不費勁,你必須非常努力,才能看起來毫不費勁." /> 15 16 <com.shxt.xkl.MaequeeText 17 android:layout_width="wrap_content" 18 android:layout_height="wrap_content" 19 android:ellipsize="marquee" 20 android:focusable="true" 21 android:focusableInTouchMode="true" 22 android:singleLine="true" 23 android:text="你必須非常努力,才能看起來毫不費勁,你必須非常努力,才能看起來毫不費勁." /> 24 25 </LinearLayout>
在新建一個TextView的子類
1 public class MaequeeText extends TextView { 2 3 public MaequeeText(Context context) { 4 super(context); 5 } 6 7 // 重寫所有的構造函數 Source==>Generate Constructors from Superclass 8 public MaequeeText(Context context, AttributeSet attrs, int defStyle) { 9 super(context, attrs, defStyle); 10 } 11 12 public MaequeeText(Context context, AttributeSet attrs) { 13 super(context, attrs); 14 } 15 16 @Override 17 public boolean isFocused() { 18 return true; 19 // 自定義設置讓focusable為true 20 // 這個方法相當於在layout中 21 // android:focusable="true" 22 // android:focusableInTouchMode="true" 23 } 24 }
以上代碼就能解決了今后多個跑馬燈的問題了,希望對大家有幫助!
~Moon童鞋