Android TextView 跑马灯效果👉两种简单方式

583 阅读1分钟

方式一

<TextView
   ...
    android:ellipsize="marquee"
    android:focusableInTouchMode="true"
    android:singleLine="true">
    <requestFocus />
</TextView>

🌴 注: 不适用于 Adapter 中。

方式二

自定义View

/**
 * 实现跑马灯效果的TextView
 */
public class MarqueeTextView extends TextView {
    private boolean mNeedFocus;
    public MarqueeTextView(Context context) {
        super(context);
    }
    public MarqueeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public MarqueeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    
    //返回 TextView 是否处在选中的状态 , 而只有选中的 TextView 才能够实现跑马灯效果
  	//等效于 xml 中 <requestFocus />
    @Override
    public boolean isFocused() {
        if (mNeedFocus) {
            return false;
        }
        return super.isFocused();
    }

    public void setNeedFocus(boolean needFocus) {
        mNeedFocus = needFocus;
    }
}

🌴 XML中:

<com.ando.player.ui.MarqueeTextView
	...
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:singleLine="true"
    tools:text="这是一个标题" />

并且在代码中动态开启/关闭跑马灯效果:

mTitle.setNeedFocus(true);//开启 true