您的位置:首页 > 其它

如何实现跑马灯效果

2016-09-26 11:21 267 查看
往往看到一些应用的标题栏中当标题超出时便会自动滚动

这篇文章要讲的就是如何去实现TextView的Marquee效果

其实TextView已经自带了如何实现滚动的属性

android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"


通过上面的属性设置就能让TextView滚动起来。当然也可以通过代码去设置。

但是当设置完之后发现并没有滚动起来,原来TextView滚动的前提是这个空间必须要获得焦点。TextView需要必须处于focus状态。

在TextView的父类View中有一个方法isFocused(),系统通过这个方法去判断一个空间是否获得焦点。

所以我们就有了解决方案:

写一个子类继承TextView,重写isFocused()方法,直接返回true。当通过这个函数去判断TextView有没有获得焦点时,总是返回获得焦点于是我们的TextView就开始滚动起来了。代码很简单:

public class AlwaysMarqueeTextView extends TextView {

/**
* constructor
* @param context Context
*/
public AlwaysMarqueeTextView(Context context) {
super(context);
}

/**
* constructor
* @param context Context
* @param attrs AttributeSet
*/
public AlwaysMarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}

/**
* constructor
* @param context Context
* @param attrs AttributeSet
* @param defStyle int
*/
public AlwaysMarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

@Override
public boolean isFocused() {
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: