Android中的TextView的跑马灯效果
两种方式实现TextView的跑马灯效果:
1.使用Android系统源生的属性实
<TextView
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_marginTop="5dp"
android:textSize="14dp"
android:textColor="#ff0000"
android:text="健康路路口上点击附件二姐姐哦我分类数据及劳务款金额及偶就"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
缺点:
1:速度不能控制,焦点不在TextView上时不能滚动。但因为这是安卓系统的功能,所以基本不用考虑兼容性。还有,当文本长度小于控件长度时也是没有跑马灯效果的。
2.使用自定义View实现跑马灯效果:
public class MarqueeTextView extends TextView {
public MarqueeTextView(Context context) {
super(context);
}
public MarqueeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 用来控制当前的view永远有焦点
* @return
*/
@Override
public boolean hasFocusable() {
return true;
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
//当有焦点的时候才调用textview的方法,没有焦点是就不调用textview的方法
if (focused){
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
}
/**
* 当窗口的焦点发生改变时调用(如dialog)
*/
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
//只有在window有焦点的时候才调用父类的方法
if (hasWindowFocus){
super.onWindowFocusChanged(hasWindowFocus);
}
}
}