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

方式一

<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

本文作者:风之旅人

本文链接:https://www.cnblogs.com/jooy/p/17302055.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   javakam  阅读(0)  评论(0编辑  收藏  举报  
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起