TextView是我们最熟悉的一个View。它的基本属性我们都很了解。TextView本色就可以实现Marquee的效果,这个只适合单个的TextView。如果你要在一个页面实现多个TextView的跑马灯效果那是无法实现的。为了达到我们想要的效果,我们必须继承TextView并重写它的方法isFocused()。效果图如下:
布局如下:
<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:padding="10dp"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="系统自带的TextView实现多个跑马灯效果"
android:textColor="#00ff00" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:text="@string/hello_world" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:text="@string/hello_world" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自定义的TextView实现多个跑马灯效果"
android:textColor="#0000ff" />
<com.yehu.marqueetextviewdemo.MarqueeTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:text="@string/hello_world" />
<com.yehu.marqueetextviewdemo.MarqueeTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:text="@string/hello_world" />
</LinearLayout>
核心类MarqueeTextView代码如下:
package com.yehu.marqueetextviewdemo;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* @author yehu
* @time 2016年1月12日下午4:53:54
*/
public class MarqueeTextView extends TextView {
public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MarqueeTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
// 核心部分
@Override
public boolean isFocused() {
return true;
}
}
哈哈!多个TextView实现跑马灯的效果就这样搞定了。