TextView属性android:ellipsize="marquee"不生效的解决办法

时间:2023-03-09 05:19:41
TextView属性android:ellipsize="marquee"不生效的解决办法

最近自己在写自己的第一个app,过程中遇到了这个问题,查了不少帖子,经过尝试发现,这种问题一般分为两类:

1. TextView的Text值赋值后不更改,很多帖子上说如下写法就可以生效:

            <TextView
android:id="@+id/music_name_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" 【必须】
android:focusable="true" 【必须】
android:focusableInTouchMode="true" 【必须】
android:lines="1" 【必须】
android:text="我的中国心我的中国心我的中国心我的中国心我的中国心我的中国心我的中国心我的中国心我的中国心xxxx"
android:textColor="@color/colorAccent"
android:textSize="15sp" />

2. TextView的文字动态赋值,这个时候直接写在布局Xml里面已经不生效了,需要先给TextView赋值,然后再在代码里面重新把属性设置一遍:

    public static void setTextMarquee(TextView textView) {
if (textView != null) {
textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
textView.setSingleLine(true);
textView.setSelected(true);
textView.setFocusable(true);
textView.setFocusableInTouchMode(true);
}
}

备注:

1. 第一种情况经过测试,在我手机上不行,即使是TextView不动态赋值,仍旧不能滚动,猜测应该是系统兼容性问题。

2. 第二种经过验证是OK的,建议直接代码赋值。