TextView的跑马灯显示

在布局中添加一个TextView:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

当显示的内容非常长的时候,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:text="@string/hello_world" />

我们发现,增加了singleLine, ellipsize, focuable 和focusableInTouchMode这四个属性以后,TextView就可以实现我们想要的效果了。

singleLine 属性用来指定TextView只能单行显示;

ellipsize 用来指定TextView 的省略方式。这里使用marquee,也就是跑马灯的省略方式;

按道理来说,添加这两个属性应该就够了,为什么还要加上focusable 和focusableInTouchMode 这两个属性呢?我也并不非常明白,我认为是因为marquee的效果只有在当前控件获取焦点以后才有用,所以要添加focusable 和focusableInTouchMode来让TextView获取焦点。

这也能解释另外一个问题:当布局中有多个TextView的时候,只有第一个TextView能显示跑马灯的效果。想要解决这个问题,可以实现一个TextView的子类来继承TextView,重写其中的isFocused方法:

public class MyTextView extends TextView {

	public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		// 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
	public boolean isFocused() {
		return true;
	}

	
}

在这个子类里重写了父类所有的构造方法和isFocused 方法,让其返回true。也就是让两个所有的MyTextView 都获取焦点。

最后将布局中的TextView改成自定义的MyTextView

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值