Android TextView 实现跑马灯的效果很简单,只要加三个属性就可以了。
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
上面的代码简单实用,但仅限于当前页面只有一个跑马灯的TextView 的实现。如果页面有两个或者是更多的跑马灯效果的时候,除了第一个TextView,其他的跑马灯效果就不会动了。
找了一下原因,是因为要实现跑马灯的效果,TextView 必须要得到焦点。当一个页面有许多跑马灯的时候,默认的第一个TextView已经把焦点占据了。
因此别的跑马灯也就无法获取焦点了。
要想一个页面上同时实现多个跑马灯效果怎么办呢?其实也很简单。
写一个类继承TextView
重写里面的isFocused ()方法(直接返回true)
调用自己写的TextView控件
我们把所有的TextView创建时都强制获取焦点。
相关布局和代码如下:
<com.mili.smarthome.tkj.ui.widget.MarqueeTextView
android:layout_width="@dimen/dp_122"
android:layout_height="wrap_content"
android:singleLine="true"
android:focusable="true"
android:ellipsize="marquee"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:text="测试TextView走马灯效果"
android:textColor="@color/txt_white"
android:textSize="@dimen/sp_20"/>
package com.*****.ui.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
import androidx.annotation.Nullable;
@SuppressLint("AppCompatCustomView")
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);
}
public MarqueeTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean isFocused() {
return true;
}
}
其中TextView相关属性含义:
singleLine:内容单行显示
focusable:是否可以获取焦点,跑马灯效果要求必须获取焦点
focusableInTouchMode:用于控制视图在触摸状态下是否可以聚焦
ellipsize:在哪里省略文本,跑马灯效果需选择marquee
marqueeRepeatLimit:字幕动画重复次数,marquee_forever无限循环