Android TextView文字橫向自動滾動(跑馬燈)

fmms 12年前發布 | 48K 次閱讀 Android Android開發 移動開發
TextView實現文字滾動需要以下幾個要點:
1.文字長度長于可顯示范圍:android:singleLine="true"
2.設置可滾到,或顯示樣式:android:ellipsize="marquee"
3.TextView 只有在獲取焦點后才會滾動顯示隱藏文字,因此需要在包中新建一個類,繼承TextView。重寫isFocused方法,這個方法默認行為是,如果 TextView獲得焦點,方法返回true,失去焦點則返回false。跑馬燈效果估計也是用這個方法判斷是否獲得焦點,所以把它的返回值始終設置為 true。

以下轉自他人:

public class AlwaysMarqueeTextView extends TextView {

public AlwaysMarqueeTextView(Context context{
super(context);
}

public AlwaysMarqueeTextView(Context context, AttributeSet attrs{
super(context, attrs);
}

public AlwaysMarqueeTextView(Context context, AttributeSet attrs, int defStyle{
super(context, attrs, defStyle);
}

@Override
public boolean isFocused() {
return true;
}

在布局XML文件中加入這么一個AlwaysMarqueeTextView,這個加入方法也是剛剛學的。

XML語言layout.xml
<com.examples.AlwaysMarqueeTextView
android:id=“@+id/AMTV1″
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:lines=“1″
android:focusable=“true”
android:focusableInTouchMode=“true”
android:scrollHorizontally=“true”
android:marqueeRepeatLimit=“marquee_forever”
android:ellipsize=“marquee”
android:background=“@android:color/transparent”
/>

ellipsize屬性
設置當文字過長時,該控件該如何顯示。有如下值設置:”start”—–省略號顯示在開頭;”end”——省略號顯示在結尾;”middle”—-省略號顯示在中間;”marquee” ——以跑馬燈的方式顯示(動畫橫向移動)

marqueeRepeatLimit屬性
在ellipsize指定marquee的情況下,設置重復滾動的次數,當設置為marquee_forever時表示無限次。

focusable屬性
自己猜測的,應該是能否獲得焦點,同樣focusableInTouchMode應該是滑動時能否獲得焦點。

組合View的問題:

XML語言組合View
< LinearLayout
xmlns:android =“http://schemas.android.com/apk/res/android”
android:orientation =“vertical”
android:gravity =“center_vertical”
android:background =“@drawable/f_background”
android:layout_width =“fill_parent”
android:focusable =“true”
android:layout_height =“50px” >
< TextView
android:id =“@+id/info_text”
android:focusable =“true”
android:layout_width =“fill_parent”
android:layout_height =“wrap_content”
android:text =“test marquee  .. “
android:textColor =“@color/black”
android:singleLine =“true”
android:ellipsize =“marquee”
android:marqueeRepeatLimit =“3″
android:textSize =“18sp”
/>
< TextView
android:id =“@+id/date_text”
android:layout_width =“fill_parent”
android:layout_height =“wrap_content”
android:layout_gravity =“bottom”
android:textColor =“@color/gray”
android:text =“2010/05/28″
android:textSize =“12sp”
/>
</ LinearLayout >

上面示例中2個TextView組合為一個View,由于設置了LinearLayout為focusable而TextView就沒法取得焦點了,這樣 這個TextView的跑馬燈效果就顯示不出來,就算你也設置TextView的 android:focusable="true" 也是 沒用的. 這個時候就要使用addStatesFromChildren 這個屬性了,在LinearLayout中設置這個屬性,然后設置TextView的focusable= "true" 就可以了.關于 addStatesFromChildren的說明:

Sets whether this ViewGroup's drawable states also include its children's drawable states.

 本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!