要想实现一直循环的跑马灯效果,需要重写isFocused()
方法使其一直处于获取焦点状态,并且onFocusChanged()
里面不能调用父类的方法,否则跑马灯将会停止。下面是自定义的跑马灯TextView。
public class MarqueeTextView extends AppCompatTextView {
public MarqueeTextView(Context context) {
super(context);
}
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MarqueeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean isFocused() {
return true;
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(true, direction, previouslyFocusedRect);
}
}
在XML文件中使用方法,里面的这些属性不能缺少:
<com.gaoshijie.android.marqueetextview.MarqueeTextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:marqueeRepeatLimit="marquee_forever" />