首先要牢记一点:即Android布局中默认只能有一个view获得焦点,不可能存在多个view同时获得焦点的情况.
一.
如果只需要让唯一 一个TextView实现走马灯的话,可以直接在布局文件中为该 TextView添加以下五个个属性即可:
android:singleLine=”true”单行显示
android:ellipsize=”marquee”走马灯样式
android:focusable=”true”
android:focusableInTouchMode=”true”
android:marqueeRepeatLimit=”marquee_forever”
二.避免EditText和Dialog抢占了焦点而停止
如果需要让多个TextView同时实现走马灯,或者同一布局中在编辑EditText时或在弹出了Dialog后走马灯能继续执行的话,就与上面说的一个布局中只能有一个view获得焦点矛盾了,该怎么办呢,这时需要自定义 TextView了.
public class FocusedTextView extends TextView {
// 如果需要在代码中new该自定义TextView时用的constructor
public FocusedTextView(Context context) {
this(context, null);
}
// 如果需要将该自定义TextView copy qualify name到布局文件中,这个constructor就是为编译器准备的
public FocusedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
//代码设置走马灯的五个必备属性
setEllipsize(TruncateAt.MARQUEE);
setFocusable(true);
setFocusableInTouchMode(true);
setMarqueeRepeatLimit(-1);//-1即永远执行
setSingleLine();
}
//该方法返回true,是为了让多个需要同时实现走马灯的TextView相信其本身是获得焦点的
@Override
public boolean isFocused() {
return true;
}
//避免编辑EditText时走马灯停止的必要实现
@Override
protected void onFocusChanged(boolean focused, int direction,Rect previouslyFocusedRect) {
if (focused) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
}
//避免弹出dialog后走马灯停止的必要实现
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
if (hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
}
}
}