第一种方式:
<com.example.myapplication.FocusTextView
android:layout_marginTop="10dp"
android:id="@+id/tv"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="淡黄的长裙蓬松的头发牵着我的手看最新展出的油画无人的街道在空荡的家里就只剩我一个人狂欢的party"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
注意:FocusTextView已经重写isFocused()方法 返回true, 所以android:focusableInTouchMode="true" android:focusable="true" 这2个属性不用写,写上当其他控件获取焦点后 跑马灯效果失效。
public class FocusTextView extends androidx.appcompat.widget.AppCompatTextView {
public FocusTextView(Context context) {
super(context);
}
public FocusTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public FocusTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean isFocused() {
return true;
}
}
第二种方式:
<TextView
android:layout_marginTop="10dp"
android:id="@+id/tv"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="淡黄的长裙蓬松的头发牵着我的手看最新展出的油画无人的街道在空荡的家里就只剩我一个人狂欢的party"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
java代码中: mtv.setSelected(true);//必须写
第三种方式:
<TextView
android:layout_marginTop="10dp"
android:id="@+id/tv"
android:focusableInTouchMode="true"
android:focusable="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="淡黄的长裙蓬松的头发牵着我的手看最新展出的油画无人的街道在空荡的家里就只剩我一个人狂欢的party"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
总结:
第一种方式和第二种方式 效果一样,当有其他控件获取焦点时,跑马灯任会重开始滚动;第三种方式 当有其他控件获取焦点时,跑马灯停止滚动,所以推荐方法一、二。
对应的xml属性也可以在java代码中写:
mtv.setSingleLine();
mtv.setEllipsize(TextUtils.TruncateAt.MARQUEE);
mtv.setMarqueeRepeatLimit(-1);//-1表示无限循环