1、一般TextView只有在取得焦点时才会实现跑马灯效果。需要设置属性
android:singleLine=”true”
android:ellipsize=”marquee”
android:focusableInTouchMode=”true”
android:focusable=”true”
另外,layout_width要比text长度长。
android:marqueeRepeatLimit=”marquee_forever”表示一直滚动。
2、TextView没有取得焦点时也实现跑马灯效果,可以自定义一个MarqueeTextView 继承 TextView,并重写相应的方法。具体代码如下:
public class MarqueeTextView extends TextView
{
private Context context;
/**构造方法
* @param context
*/
public MarqueeTextView(Context context)
{
super(context);
this.context = context;
}
/**
* @param context
* @param attrs
*/
public MarqueeTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
this.context = context;
}
/**
* @param context
* @param attrs
* @param defStyle
*/
public MarqueeTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
/**
* @param focused
* @param direction
* @param previouslyFocusedRect
*/
@Override
protected void onFocusChanged(boolean focused, int direction,
Rect previouslyFocusedRect)
{
// TODO Auto-generated method stub
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
/**
* @param hasWindowFocus
*/
@Override
public void onWindowFocusChanged(boolean hasWindowFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasWindowFocus);
}
/**
* @return
*/
@Override
public boolean isFocused()
{
return true;
}
相应xml文件中自定义控件设置如下:
<MarqueeTextView android:id="@+id/bitmap_name" android:layout_width="200dip"
android:background="#DCDCDC" android:layout_height="50dip"
android:layout_centerHorizontal="true"
android:text="name" android:textColor="#6E6E6E" android:textSize="24sp"
android:gravity="center" android:ellipsize="marquee"
android:singleLine="true" android:marqueeRepeatLimit="marquee_forever"
/>