最近项目中经常使用到跑马灯的效果,比如说一个通知等等,都可以用跑马灯的效果来实现,也是项目中经常要使用的到,现在我们就来总结归纳一下android项目中如何实现跑马灯的效果,首先第一种就是android自带的跑马灯的效果,直接上代码吧:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:ellipsize="marquee"//设置跑马灯的效果
android:focusable="true"//必须设置为true,获得焦点,这样才会跑马灯的效果
android:focusableInTouchMode="true"//必须设置为true,获得焦点,这样才会跑马灯的效果
android:singleLine="true"//必须是singleLine,如果是lines="1"的话没有效果
android:marqueeRepeatLimit="marquee_forever"//跑马灯的重复设置
android:scrollHorizontally="true"
android:text="@string/marquee_text" />
这种方法的优点是:代码简单,只要设置一下属性就可以了,缺点是:只能在TextView中实现跑马灯的效果,不能实现其他控件,方向固定,速度固定。
第二种就是我自己写的MarqueeLnearLayout,话不多说直接上代码:
<com.lx.lxlibrary.view.MarqueeLinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@color/c3"
android:gravity="center"
app:direction="left"//设置方向
app:marquee_speed="20">//设置速度
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/c4"
android:scrollbars="none">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:src="@mipmap/activity" />
<TextView
android:id="@+id/tv_left"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:maxLines="1"
android:text="@string/marquee_text" />
</LinearLayout>
</HorizontalScrollView>
</com.lx.lxlibrary.view.MarqueeLinearLayout>
第二种的方法缺点是:代码设置会复杂一些,必须使用ScrollView嵌套一层,这个到后期还会修改与改进。优点是可以设置方向,速度,还有其中的布局可以自己设定,不仅仅是TextView可以实现跑马灯的效果。还是十分实用的!现在看一下效果:
:
第一行是普通TextView设置的方法
后面几行是MarqueeLinearLayout布局设置出来的效果
截图代码下载地址:点击打开链接