问题描述
我的应用中有一个用 TextView
定义的 marquee_forever
:
<TextView
android:id="@+id/networkNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@color/wefiPrimaryColor"
android:textSize="15sp"
android:textStyle="bold" />
它在小米 Android 8.1 上完美运行,但在 galaxy Note Android 10 上却无法运行。
相反,我得到 android:ellipsize
。
是否需要新参数或者这是 Android 10 或 galaxy Note 的问题?
解决方法
您有两种方法可以做到这一点。如果TextView
填充整个宽度需要添加这些代码行
<TextView
.
.
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
/>
也不要忘记为TexrtView
设置selected
textview.setSelected(true);
如果 TextView
没有填充宽度,唯一的方法就是调用这个方法并将 TextView
传递给它。
fun addMarquee(textView: TextView) {
textView.viewTreeObserver.addOnGlobalLayoutListener(object :
ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val pixels = textView.measuredWidth - 1
val params = textView.layoutParams
params.width = pixels
textView.layoutParams = params
textView.isSelected = true
textView.ellipsize = TextUtils.TruncateAt.MARQUEE
textView.isSingleLine = true
textView.marqueeRepeatLimit = -1
textView.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
}
注意:此方法仅在 textView 宽度为 wrap_content
时有效。