天天看点

Android拓展TextView 实现跑马灯效果

自定义一个View

//package 你的包名;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
//继承自TextView 实现跑马灯效果
public class ScrollForeverTextView extends TextView {   

    public ScrollForeverTextView(Context context) {   
        super(context);   
    }   

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

    public ScrollForeverTextView(Context context, AttributeSet attrs,   
            int defStyle) {   
        super(context, attrs, defStyle);   
    }   

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

使用

xml文件中

<!--ScrollForeverTextView前面加上自定义控件所在的包名-->
<ScrollForeverTextView
        android:id="@+id/sftv"
        android:layout_width="fill_parent"
        android:layout_height="32dp"
        android:ellipsize="marquee"
        android:focusable="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:singleLine="true"
        android:gravity="center"
        android:textSize="12sp"
        android:background="#78cdf8"
        android:layout_marginTop="45dip"
        android:text="这是跑马灯的效果这是跑马灯的效果这是跑马灯的效果这是跑马灯的效果这是跑马灯的效果这是跑马灯的效果"
        android:textColor="@android:color/white"/>
           

最后,findView并设置文本,如果文本长度大于控件的宽度,文本则滚动。