android使用TextView实现文字的跑马灯效果

本节的内容学习自慕课网,记录下来以便复习和查阅!


当布局文件比较单一,比如只有一个需要实现跑马灯的TextView时,可以直接通过设置TextView的属性来实现效果;

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:layout_margin="10dp"
        android:text="@string/hello_world" />

android:ellipsize="marquee"属性设置使得当文字超过TextView宽度是实现文字滚动,但是又必须在TextView获取到焦点才能实现文字滚动效果,所以还需设置属性:

android:focusable="true" 和 android:focusableInTouchMode="true"


当布局文件比较复杂的时候,比如有两个TextView需要实现跑马灯效果;这个时候通过设置TextView的属性会发现只有第一个TextView实现了跑马灯效果,因为焦点一直在第一个TextView上,所以第二个TextView没有获取到焦点也就没有实现跑马灯的效果;

解决的方法是自定义一个类继承TextView;然后重写其中的isFocused();如:

public class MyTextView extends TextView {

	public MyTextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	public MyTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public MyTextView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	@ExportedProperty(category = "focus")
	public boolean isFocused() {
		return true;
	}

}

 <com.example.mooc.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:layout_margin="10dp"
        android:text="@string/hello_world" />
    
    <com.example.mooc.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:layout_margin="10dp"
        android:text="@string/hello_world" />

将该方法的返回值直接写成true,这样在布局文件中创建的所有MyTextView则都能够获取到焦点了;也就能够实现两个TextView的跑马灯效果了;

例外,android:marqueeRepeatLimit属性可以设置跑马灯的循环次数,如:android:marqueeRepeatLimit="-1"表示无限循环次数,android:marqueeRepeatLimit="1" 则表示支循环播放一次;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值