實現一個有趣的小效果

假裝它是動起來的,實現的是一個跑馬燈效果
一、新建一個Project。

二、添加兩個TextView,並設置它的屬性。

 <TextView
        android:id="@+id/tv_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="瘋狂源自夢想,技術成就輝煌,好好學習,天天向上!!!"
        android:textSize="24dp"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:textColor="#b1704a"
        />
    <TextView
        android:layout_below="@+id/tv_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="瘋狂源自夢想,技術成就輝煌,好好學習,天天向上!!!"
        android:textSize="64dp"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:textColor="#ff0000"
        />

android:singleLine=”true”
設置單行顯示。
如果和layout_width一起使用,當文本不能全部顯示時,後面用“…”來表示。


android:ellipsize=”marquee”
.設置可滾動,或顯示樣式


android:focusable=”true”:設置TextView自動獲得焦點
android:focusableInTouchMode=”true”:通過觸摸獲得焦點


這些屬性設置完畢之後,運行一下,你會發現第一個TextView會有跑馬燈效果,第二沒有,這是因爲程序一運行,先是第一個TextView或的焦點,一直沒有丟失,所以第二個TextView才獲取不到。也就沒有效果。

如果需要兩個TextView都能完美運行,自定義TextView,這時我們需要新建一個類來繼承TextView。實現它的三個構造方法。並覆蓋isFocused()方法,返回值設置爲true,這樣就強制性要求了這自定義TextView子類都獲得焦點。

public class MarqueeText extends TextView{
    public MarqueeText(Context context) {
        super(context);
    }

    public MarqueeText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MarqueeText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}

然後我們在把TextView換成我們自定義的TextView,就OK了。

 <com.zp.administrator.marqueetextviewdemo.MarqueeText
        android:id="@+id/tv_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="瘋狂源自夢想,技術成就輝煌,好好學習,天天向上!!!"
        android:textSize="24dp"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:textColor="#b1704a"
        />
    <com.zp.administrator.marqueetextviewdemo.MarqueeText
        android:layout_below="@+id/tv_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="瘋狂源自夢想,技術成就輝煌,好好學習,天天向上!!!"
        android:textSize="64dp"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:textColor="#ff0000"
        />

接着再運行就可以看到兩個效果都實現了。

ps:今天是自己第一次寫技術博客,雖然這只是開始的一小步,卻是我作爲程序員的一大進步。O(∩_∩)O~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章