TextView跑步灯效果及在特殊情况下无效的解决方案

概述:

  关于在TextView中使用跑马灯效果的例子在网上一搜一大把。他们可能会让你像下面这样来在xml中定义TextView控件的属性。而事实也确是如此。不过我不知道他们有没有遇到和我一样的问题(其实我感觉是有的),我们第一次运行程序的时候,跑马灯没有效果,当我们关闭activity或是fragment再次进入的时候,跑马灯的效果又有了。


一般情况:


<TextView
                        android:id="@+id/textview1"
                        android:layout_width="200dp"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_toRightOf="@id/main_has_connected_textView"
                        android:text="TextView"
                        android:singleLine="true"
                        android:ellipsize="marquee"
                        android:focusable="true"
                        android:marqueeRepeatLimit="marquee_forever"
                        android:focusableInTouchMode="true"
                        android:scrollHorizontally="true"
                        android:textSize="22sp" />

修改之后:

如上的代码,一些基本的该设置的属性都已经设置好了。不过还是会出现第一次运行无效果的情况。这种情况出现的原因应该是TextView在获得焦点的时候,会有丢失。我们可以动态地为这个TextView添加一些事件。不过为了方便和安全性,我们可以将其放在它的自定义控件中。

这个时候我们就需要在java代码中来动态实现了。如下:

public class FlowTextView extends TextView {
    
    public FlowTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

    public FlowTextView(Context context) {
        super(context);
    }

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

}


xml中的使用与之前的无差别,如下:

<com.demo.widgets.FlowTextView
                        android:id="@+id/main_connect_fs_name"
                        android:layout_width="200dp"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:text="TextView"
                        android:singleLine="true"
                        android:textColor="#ffFFFFFF"
                        android:ellipsize="marquee"
                        android:focusable="true"
                        android:marqueeRepeatLimit="marquee_forever"
                        android:focusableInTouchMode="true"
                        android:scrollHorizontally="true"
                        android:textSize="22sp" />



原文地址:https://www.cnblogs.com/fengju/p/6336100.html