閱讀307 返回首頁    go 財經資訊


android: 不需要焦點的TextView跑馬燈 MarqueeTextView

之前在網上找了很多關於TextView的跑馬燈效果實現的例子,實現起來都存在一些問題,例如一種是完全重畫一個跑馬燈,還有就是隻設置TextView的相關屬性使其具有跑馬燈的效果,總的來說這兩種方法都是可行的,但是都有其不足之處,第一種太複雜,實現起來比較麻煩,第二種呢,它隻能在TextView獲得焦點的時候才有跑馬燈的效果,這樣有時候並不能達到我們所要求的效果。我通過網上的一些例子自己在做了一些改動,就實現了現在不用獲取焦點也能“跑”起來的效果。具體代碼如下
首先,寫一個類,讓其繼承自TextView:
public class MarqueeText extends TextView {
public MarqueeText(Context con) {
  super(con);
}

public MarqueeText(Context context, AttributeSet attrs) {
  super(context, attrs);
}
public MarqueeText(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
}
@Override
public boolean isFocused() {
return true;
}
@Override
protected void onFocusChanged(boolean focused, int direction,
   Rect previouslyFocusedRect) {  
}
}

然後再將我們已經寫好的這個控件(MarqueeText)放到布局文件中,例如main.xml:
<TextView android:layout_width="400dip"
        android:layout_height="wrap_content"        
        android:layout_marginLeft="80dip"
        android:layout_marginBottom="25dip"
        android:textSize="25sp"        
        android:textColor="@android:color/black" 
        android:ellipsize="marquee" 
        android:focusable="true" 
        android:marqueeRepeatLimit="marquee_forever" 
        android:focusableInTouchMode="true" 
        android:scrollHorizontally="true"
        android:text="這才是真正的文字跑馬燈效果,文字移動速度,文字移動方向,文字移動的樣式,動畫等等……"
        android:background="#2FFFFFFF"        
        >
    </TextView>
<!-- 在布局文件中用自己寫的控件隻需要寫類的全名就行,如下com.example.    這是包名,後麵再跟類名就行了 -->
  <com.example.MarqueeText
    android: 
    android:layout_width="400dip"
    android:layout_height="wrap_content"        
    android:layout_marginLeft="80dip"    
    android:textSize="25sp"        
    android:textColor="@android:color/black" 
    android:lines="1"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:scrollHorizontally="true"  
    android:marqueeRepeatLimit="marquee_forever"  
    android:ellipsize="marquee" 
    android:background="#2FFFFFFF"
    android:text="這才是真正的文字跑馬燈效果,文字移動速度,文字移動方向,文字移動的樣式,動畫等等……"
    />


前一個TextView是用Android自帶的跑馬燈效果,後一個就是咱自己的。至於Activity中怎麼寫這裏就不多說了,沒有什麼特殊的設置。
關於MarqueeText類中為什麼要複寫onFocusChanged()方法,那是因為如果不寫,在Textview 獲得焦點後,再失去焦點時 字就會停止“跑”了,所以如果想讓它一直跑下去就複寫onFocusChanged(),並且裏麵什麼也不做(主要是不能調用父類的方法)。

最後更新:2017-04-02 16:47:52

  上一篇:go apache 版本信息控製
  下一篇:go wait和sleep的區別 以及 實例演示