使用TextView实现跑马灯效果

本文介绍如何使用TextView组件在Android应用中实现跑马灯滚动文字效果。主要通过设置singleLine、ellipsize、focusable等属性,并通过自定义TextView类重写isFocused方法确保效果始终生效。

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

使用TextView实现跑马灯效果

分为几个步骤,
一、首先设置layout文件

<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:text="@string/hello_world"/>

加入singleLine,ellipsize = marquee,focusable,focusableInTouchMode = “true”。这样就可以实现了跑马灯效果

随后再加入一个TextView后,只有第一个TextView存在跑马灯效果,所以要用Focu强制转一下
方法如下:

二、新建一个class文件,继承TextView,加入其中三个构造器。
随后复写一个isFocused()。

public class MarqueeTest extends TextView {
    public MarqueeTest(Context context) {
        super(context);
    }

    public MarqueeTest(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MarqueeTest(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}

最后一把,在Layout中,将TextView的<TextView———>替换为:<com.yourname.clicklinstener.MarqueeTest这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值