1. 程式人生 > >Android TextView實現滾動跑馬燈效果Marquee

Android TextView實現滾動跑馬燈效果Marquee

可以利用原生功能實現效果:

1、如果TextView中的文字過長,(在失去焦點時)那麼超出顯示範圍的文字以...顯示

2、如果TextView獲得了焦點,那麼其中的文字以迴圈滾動的方式顯示

佈局中程式碼如下:

<com.asdf.app.widget.autoscrolltextview.AutoTextView
        android:id="@+id/showMarquee"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/colorFFF7D6"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:gravity="center"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:singleLine="true"
        android:textColor="@color/colorff6600" />
其中:

1、

android:ellipsize="marquee" //跑馬燈效果</span>

2、

android:focusable="true"//是否獲取焦點

3、

android:focusableInTouchMode="true"//通過Touch獲取焦點

4、

android:marqueeRepeatLimit="marquee_forever"//無限迴圈,如果設定值為正數則就是迴圈滾動的次數
程式碼設定為:
textView.setMarqueeRepeatLimit(-1);         

5、

android:singleLine="true"//單行顯示
程式碼設定為:
  1. textView.setSingleLine(true);  

6、當焦點離開該TextView時,取消該TextView的滾動效果

textView.setEllipsize(TruncateAt.END);      //尾部無法顯示的文字以...表示

7、以上佈局屬性設定完畢,重點還有一個:

public class AutoScrollTextView extends TextView {
    public AutoScrollTextView(Context context) {
        super(context);
    }

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

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

    @Override
    public boolean isFocused() {//必須重寫,且返回值是true
        return true;
    }
}

8、差點忘了另外一個重點需要許可權</span>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

9、上面準備完了,基本上也就成功了

就是在程式碼中像TextView一樣進行賦值等操作就Ok了,

如果文字長度小於控制元件的長度可能不會滾動,加空格試試??

希望對大家有幫助,,歡迎指點批評!