项目开发中有些时候TextView的文本内容太长了显示不全,这个时候需要让它实现像网页上面的跑马灯效果,网上很多文章都是自定义控件继承自TextView来实现的,自己在实践中发现不用自定义控件也可以实现跑马灯的效果,因为Android原生的TextView已经支持跑马灯的效果了。
关键之处在于设置TextView的四个属性值:
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
尤其是下面两个属性:
android:focusable="true"
android:focusableInTouchMode="true"
只有当它获取到焦点的时候才会滚动。
完整布局如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="@string/txt_title"
android:textSize="15sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/confirm"
android:textSize="15sp"/>
</LinearLayout>