效果图:
布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:id="@+id/tvTip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFDE9EB"
android:singleLine="true"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:paddingLeft="10dp"
android:paddingTop="12dp"
android:paddingRight="10dp"
android:paddingBottom="12dp"
android:text="物流公告:受疫情影响,2020-08-20起,深圳地区暂时不支持发货"
android:textColor="#FFEB2C3E"
android:textSize="15sp">
<requestFocus/>
</TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
设置以下属性:
android:singleLine="true"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever
这句很重要
如果界面即存在textview跑马灯效果还存在刷新refresh或edittext要把跑马灯布局给抽取出去
<include
android:layout_below="@+id/lineView"
android:id="@+id/pmdLay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/include_pmd_view"/>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:id="@+id/tvTip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/lineView"
android:background="@color/red_ffd"
android:singleLine="true"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:paddingLeft="@dimen/dp_10"
android:paddingTop="@dimen/dp_12"
android:paddingRight="@dimen/dp_10"
android:paddingBottom="@dimen/dp_12"
android:text="物流公告:受疫情影响,2020-08-20起,深圳地区暂时不支持发货"
android:textColor="@color/red_ffe"
android:textSize="@dimen/sp_15">
<requestFocus/>
</TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
有时切换后textview跑马灯效果失效需要添加以下代码
//设置跑马灯效果,避免跑马灯效果失效
private fun setMarqueeText() {
tvMarqueeTip.ellipsize = TextUtils.TruncateAt.MARQUEE
tvMarqueeTip.isSingleLine = true
tvMarqueeTip.isSelected = true
tvMarqueeTip.isFocusable = true
tvMarqueeTip.isFocusableInTouchMode = true
}