只有一个需要实现跑马灯效果的TextVIew
在xml布局文件中加入一个TextView控件
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:singleLine="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:text="这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本" />
注意其中的ellipsize、singleLine、focusable、focusableInTouchMode三个属性。
android:singleLine ——设置单行显示。如果和layout_width一起使用,当文本不能全部显示时,后面用“…”来表示。如android:text=”test_ singleLine “android:singleLine=”true”android:layout_width=”20dp”将只显示“t…”。如果不设置singleLine或者设置为false,文本将自动换行
android:ellipsize——设置当文字过长时,该控件该如何显示。有如下值设置:”start”—–省略号显示在开头;”end”——省略号显示在结尾;”middle”—-省略号显示在中间;”marquee” ——以跑马灯的方式显示(动画横向移动)
android:focusable——view是否具有接受焦点的资格
android:focusableInTouchMode——对应在触摸模式下,view是否具有焦点的资格
有多个需要实现跑马灯效果的TextView
如果直接按照上面的xml布局复制一个TextView,第二个TextView会出现无法获得焦点,从而不会出现跑马灯效果的情况。
所以我们需要新建一个类继承自TextView,通过Override Isfocused()方法来使第二个textview也获得焦点。
public class MarqueeText extends TextView {
public MarqueeText(Context context) {
super(context);
}
public MarqueeText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MarqueeText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean isFocused(){
return true;
}
}
记得将xml的TextVIew修改为包中的Marquee,之后可以不写focusable和focusableInTouchMode两个属性
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="lqy.marquee_demo.MainActivity">
<lqy.marquee_demo.MarqueeText
android:id="@+id/marqueetext1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:text="这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本" />
<lqy.marquee_demo.MarqueeText
android:id="@+id/marqueetext2"
android:layout_below="@+id/marqueetext1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:text="这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本" />
</RelativeLayout>