圖1 TextView實現自動滾動效果圖
第一步、創建一個自定義的類,讓它繼承TextView,然後添加默認方法,爲以後擴展你的TextView,添加所有方法,其方法分別是:
public AutoScrollTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public AutoScrollTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public AutoScrollTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
第二步、要實現文本從一生下來就自動滾動,那麼就需要文本聚焦,而Android的TextView從生下來是沒有聚焦的,要實現自動聚焦,那就自己複寫TextView,這也是我現在講解的東西。爲了能夠實現自動滾動,我可以採用欺騙的手段,來達到目的,其原理是在我們的TextView一生下來時,我就讓它聚焦,就像我們一生下來的時候明明是男孩,但是我通過人工手術變成了女孩,其本質還是男孩,只是欺騙了別人,我們就欺騙操作系統,讓TextView有聚焦的能力,其做法如下:
繼承父類的聚焦函數:
@Override
public boolean isFocused(){
//在這裏我們告訴操作系統,我已經聚焦了
return true;
}
做完這裏之後,用你自定義的組件便可以實現文本自動滾動,而不用點擊聚焦後才滾動。
但是,需求總是遠遠不能滿足,小編髮現這樣做了之後,只能從xml對TextView的顯示內容進行初始化,並不能通過Java代碼初始化,因爲我們在繼承父類的時候並沒有如下這個方法:
this.findViewById(R.id.textView).setText("");
這樣結果實在是讓人無語,上面的精力白費了,沒關係,讓小編我來帶你飛。
第四步、繼承父類的setText()方法和getText()方法,代碼如下:
@Override
public void setText(CharSequence text, BufferType type) {
// TODO Auto-generated method stub
super.setText(text, type);
}
@Override
@CapturedViewProperty
public CharSequence getText() {
// TODO Auto-generated method stub
return super.getText();
}
然後自定義一個setText()方法,必須加final,編譯器也會提示你,代碼如下:
public final void setText(String text){
setText(text,mBufferType);
}
到這裏之後,你會發現,要實現自己的setText()方法,只能調用父類的setText(CharSequence text, BufferType type)方法,因爲父類的方法中並沒參數類型爲String的方法,而直接用CharSequence會出現錯誤,所以我們只能去調用setText(CharSequence text, BufferType type)方法,而調用這個方法時需要一個mBufferType參數,我們並不知道是啥,當然我們也不用管,在父類中找到這個變量,考過來,代碼如下:
private BufferType mBufferType = BufferType.NORMAL;
至此,一個省下來就可以自己滾出家的,又能動態改變顯示內容的TextView就被我們造出來了,當你需要別的方法,以同樣的方法,這裏只是給初學者一個小小的自定義組件的參考,由於小編才疏學淺,如有錯誤,還望指正,萬分感謝!
爲方便初學者理解,以下是完整代碼:
public class AutoScrollTextView extends TextView {
private BufferType mBufferType = BufferType.NORMAL;
public AutoScrollTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public AutoScrollTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public AutoScrollTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
public boolean isFocused(){
return true;
}
@Override
@CapturedViewProperty
public CharSequence getText() {
// TODO Auto-generated method stub
return super.getText();
}
@Override
public void setText(CharSequence text, BufferType type) {
// TODO Auto-generated method stub
super.setText(text, type);
}
public final void setText(String text) {
setText(text, mBufferType);
}
}