android项目实现跑马灯效果

本文介绍了在Android项目中实现跑马灯效果的两种方法。第一种利用Android自带的特性,通过代码展示实现过程。第二种是作者自定义的MarqueeLinearLayout,同样给出了详细代码。文章还提供了截图和代码下载链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近项目中经常使用到跑马灯的效果,比如说一个通知等等,都可以用跑马灯的效果来实现,也是项目中经常要使用的到,现在我们就来总结归纳一下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布局设置出来的效果




截图代码下载地址点击打开链接




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值