多个TextView跑马灯效果实现

本文介绍了如何实现多个TextView的跑马灯效果,关键在于设置android:ellipsize="marquee"、android:focusable="true"等属性,并创建自定义的marqueeTextView类,通过覆盖isFocused方法确保始终显示滚动效果。

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

显示跑马灯效果的前提条件就是你的文本内容要比显示文本的外部组件长,即外部组件无法完整的显示内部的文本内容
activity_main.xml
//两个TextView
  <com.example.textview.marqueeTextView     (原本的TextView改为包名.类名)
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:ellipsize="marquee"              
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:singleLine="true"                        
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <com.example.textview.marqueeTextView
        android:id="@+id/textView1"
        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:layout_marginTop="10dp"
        android:layout_below="@+id/textView2"
        android:text="@string/hello_world2" />

android:singleLine 表示使用单行文字
android:marqueeRepeatLimit,设置走马灯滚动的次数。
android:ellipsize,设置了文字过长时如何切断文字, 如果使用走马灯效果则设为marquee.
android:focusable,Android的缺省行为是在控件获得Focus时才会显示走马灯效果

新建一个marqueeTextView.java类,继承TextView类。添加TextView的三个构造函数,使用isFocused方法实现滚动。
marqueeTextView.java
public class marqueeTextView extends TextView{
public marqueeTextView(Context context) {
super(context);
}
public marqueeTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public marqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
 @Override
 public boolean isFocused() {
 return true;
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值