天天看點

Android使用TextView實作跑馬燈效果(自定義控件)

  

對于一個長的TetxView 折行顯示是一個很好的辦法,另一種方法就是跑馬燈顯示(單行滾動)

1.折行顯示的長TextView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是一個長textView,我是一個長textView,我是一個長textView,我是一個長textView," />

</LinearLayout>      

效果:

2.不允許折行的單行文本

3.實作跑馬燈效果:

效果:(從右向左滾動)

存在問題:

對于多個textView,上面的跑馬燈效果失效

4.再加一個TextView失去跑馬燈效果

第一個有跑馬燈效果,第二個沒有

 5.如果希望多個TextView有跑馬燈效果:(自定義控件)

  5.1重寫一個類繼承TextView(三個構造方法+一個isFocused方法)

package com.example.mooc;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewDebug.ExportedProperty;
import android.widget.TextView;

public class MyTextView extends TextView{

    public MyTextView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }
    @Override
    @ExportedProperty(category = "focus")
    public boolean isFocused() {
        // TODO Auto-generated method stub
        return true;
    }
}      

   5.2xml中使用自己的TextView(包名+類名)

【當你用心寫完每一篇部落格之後,你會發現它比你用代碼實作功能更有成就感!】