TextView跑馬燈實現

跑馬燈實現要素:

1、android:singleLine="true";TextView的內容顯示爲一行。內容不滿一行不滾動顯示。內容超過控件長度,跑馬燈顯示。此處的屬性只能選擇singleLine,不能使用maxLines。

2、android:ellipsize="marquee"

3、android:focusable="true" 

4、android:marqueeRepeatLimit="marquee_forever"

5、java代碼中可以設置musicName.setSelected(true);

6、需要TextView一直保持焦點。所以需要自定義一個TextView繼承TextView,覆寫isFocused方法,返回true,使焦點一直存在。

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

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

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

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

}

通常情況下,以上幾點就可以完成跑馬燈滾動了。但是部分機型,會有一部分文本不滾動,只是將超過長度的部分在文本末尾用兩個點的省略號代替了。

爲了解決這個問題,需要使用反射機制修改底層文件ViewConfiguration中的mFadingMarqueeEnabled屬性。

參考了https://blog.csdn.net/iteye_7155/article/details/82553483

https://blog.csdn.net/shiny_dct/article/details/27701157這兩個大神的解決辦法。

Class viewConfiguration = ViewConfiguration.get(this).getClass();
for (Field field : viewConfiguration.getDeclaredFields()) {
   if (field.getName().equalsIgnoreCase("mFadingMarqueeEnabled")){
      field.setAccessible(true);
      try {
         field.setBoolean(ViewConfiguration.get(this),true);
      } catch (IllegalAccessException e) {
         e.printStackTrace();
      }
   }
}

但是需要注意的是,需要在onCreate方法中的SetContentView()方法之前使用。

 

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