一、设置属性实现
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:text="Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!"
android:singleLine="true"/>
</FrameLayout>
- android:layout_width=”200dp” //文字宽度也可以是wrap_content
- android:marqueeRepeatLimit=”marquee_forever” //表示滚动回数,这里这么设置,表示一直滚动, 也可以设置为1,2.。等
- android:ellipsize=”start” 省略号在开头
- android:ellipsize=”middle” 省略号在中间
- android:ellipsize=”end” 省略号在结尾
- android:ellipsize=”marquee” 跑马灯显示
或者在程序中可通过setEillpsize显式设置,一般是配合android:singleLine=”true”一起使用 - android:focusable=”true” //要显示该跑马灯,view必须要获得焦点,只有在取得焦点的情况 下跑马灯才会显示
- android:focusableInTouchMode:是否在触摸模式下获得焦点。
对于一个大View中有很多子View来说,同一时刻只能有一个子View获得focus!也就是说当前这一屏上 ,最多只能有一个view能有跑马灯效果,而不能多个View同事都有跑马灯效果。
二、自定义View实现
public class MarqueeTextView extends AppCompatTextView {
public MarqueeTextView(Context context) {
super(context);
}
public MarqueeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean isFocused() {
return true;
}
}
<com.my.widgets.MarqueeTextView
android:id="@+id/tv_marquee"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toLeftOf="@+id/iv_close"
android:ellipsize="marquee"
android:gravity="center_vertical"
android:marqueeRepeatLimit="marquee_forever"
android:maxLength="40"
android:singleLine="true"
android:text="111111111111111111111111111111111111111111111111111111111"
android:textColor="@color/color_msg_text"
android:textSize="13sp"
tools:ignore="HardcodedText,RtlHardcoded" />