首先要牢記一點:即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);
}
}
}