實現在一個界面裏多個TextView的跑馬燈效果

TextView 實現原生跑馬燈效果

注意:首先要保證TextView顯示不全文本纔會有效果

關鍵屬性

設置爲跑馬燈顯示

android:ellipsize="marquee"

獲取焦點
android:focusable="true"

可以通過touch來獲得focus
android:focusableInTouchMode="true"

設置重複的次數
android:marqueeRepeatLimit="marquee_forever"

單行顯示文字
android:singleLine="true"

以上屬性在xml文件設置之後運行程序,還是沒有實現效果,這是因爲還需要在代碼中動態請求焦點,使用requestFocus()方法。

自定義TextView

但是使用該方法有個問題,一個界面只能有一個控件持有售點,所以一個界面只能有一個View實現跑馬燈效果(取決於哪個最後申請焦點)。所以需要自定義。

自定義TextView完整代碼如下:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

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

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

    public MarqueeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

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

使用方法:

  1. xml文件中使用,那些關鍵屬性還是要添加上。
  2. 不需要在代碼中調用requestFocus()方法。

源碼地址:https://github.com/puppet16/MarqueeTextView

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章