1. 程式人生 > >Android TextView文字橫向自動滾動(跑馬燈)

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

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 version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height
="match_parent" android:orientation="vertical" android:focusable="true" tools:context=".MainActivity">
<com.example.administrator.marqueeprojecttest.AlwaysMarqueeTextView android:layout_marginTop="45dp" android:id="@+id/AMTV1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ellipsize="marquee" android:singleLine="true" android:text="@string/zhouenlai" /> <com.example.administrator.marqueeprojecttest.AlwaysMarqueeTextView android:layout_marginTop="45dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:ellipsize="marquee" android:singleLine="true" android:text="@string/zhouenlai2" /> </LinearLayout>

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

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

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