Android实现TextView跑马灯效果

本文介绍了两种在Android中实现TextView跑马灯效果的方法。第一种适用于单个TextView,第二种则通过自定义TextView类并重写相关方法来实现多个TextView的跑马灯效果。

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

android实现跑马灯的效果第一种是页面只有一个TextView或从上至下,从左至右的第一个TextView需要跑马灯效果,实现方式为:

<TextView
    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/text"
    android:textSize="26sp"/>

第二种方式是有多个TextView需要同时实现跑马灯效果,实现方式为自定义一个类,继承TextView,并且实现它的三个构造方法,同时实现isFocused方法,将它的返回值设置为true即可完成多个TextView跑马灯的效果,具体实现方式如下:

public class MarqueeText extends TextView {

    public MarqueeText(Context context) {
        super(context);
    }

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

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

    /* isFocused方法一定要重写 */
    @Override
    public boolean isFocused() {
        return true;
    }
}
在xml布局文件中,通过自定义的类实现TextView:
<com.example.bjtest1.MarqueeText
    android:id="@+id/tv1"
    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/text"
    android:textSize="26sp"/>

<com.example.bjtest1.MarqueeText
    android:id="@+id/tv2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:layout_marginTop="10dp"
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:text="@string/text"
    android:textSize="26sp"/>
两种方式已全部分享完毕!!!吐舌头吐舌头吐舌头



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值