Android:TextView不獲取焦點可以實現跑馬燈的效果

之前在網上找了很多關於TextView的跑馬燈效果實現的例子,實現起來都存在一些問題,例如一種是完全重畫一個跑馬燈,還有就是隻設置TextView的相關屬性使其具有跑馬燈的效果,總的來說這兩種方法都是可行的,但是都有其不足之處,第一種太複雜,實現起來比較麻煩,第二種呢,它只能在TextView獲得焦點的時候纔有跑馬燈的效果,這樣有時候並不能達到我們所要求的效果。我通過網上的一些例子自己在做了一些改動,就實現了現在不用獲取焦點也能“跑”起來的效果。

首先,寫一個類,讓其繼承自TextView:

  1. public class MarqueeText extends TextView {  
  2.  public MarqueeText(Context con) {  
  3.  super(con);  
  4. }                                      
  5. public MarqueeText(Context context, AttributeSet attrs) {  
  6. super(context, attrs);  
  7. }  
  8. public MarqueeText(Context context, AttributeSet attrs, int defStyle) {  
  9. super(context, attrs, defStyle);  
  10. }  
  11. @Override  
  12. public boolean isFocused() {  
  13. return true;  
  14. }  
  15. @Override  
  16. protected void onFocusChanged(boolean focused, int direction,  
  17. Rect previouslyFocusedRect) {  
  18. }  
  19. }  

然後再將我們已經寫好的這個控件(MarqueeText)放到佈局文件中,例如main.xml:

<!-- 在佈局文件中用自己寫的控件只需要寫類的全名就行,如下com.example這是包名,後面再跟類名就行了 -->
  1. <com.example.MarqueeText  
  2. android:id="@+id/AMTV1"  
  3. android:layout_width="400dip"  
  4. android:layout_height="wrap_content"  
  5. android:layout_marginLeft="80dip"  
  6. android:textSize="25sp"  
  7. android:textColor="@android:color/black"  
  8. android:lines="1"  
  9. android:focusable="true"  
  10. android:focusableInTouchMode="true"  
  11. android:scrollHorizontally="true"  
  12. android:marqueeRepeatLimit="marquee_forever"  
  13. android:ellipsize="marquee"  
  14. android:background="#2FFFFFFF"  
  15. android:text="這纔是真正的文字跑馬燈效果,文字移動速度,文字移動方向,文字移動的樣式,動畫等等……"  
  16. />  

關於MarqueeText類中爲什麼要複寫onFocusChanged()方法,那是因爲如果不寫,在Textview 獲得焦點後,再失去焦點時字就會停止“跑”了,所以如果想讓它一直跑下去就複寫onFocusChanged(),並且裏面什麼也不做(主要是不能調用父類的方法)。

發佈了52 篇原創文章 · 獲贊 24 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章