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()方法之前使用。

 


版权声明:本文为qq_30234677原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。