您的位置:首页 > 移动开发 > Android开发

TextView的跑马灯显示

2015-09-18 17:06 447 查看
在布局中添加一个TextView:

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

当显示的内容非常长的时候,TextView 默认会分多行显示。如果想要在同一行中进行滚动显示,也就是我们所说的跑马灯效果,需要增加几个属性:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:text="@string/hello_world" />

我们发现,增加了singleLine, ellipsize, focuable 和focusableInTouchMode这四个属性以后,TextView就可以实现我们想要的效果了。
singleLine 属性用来指定TextView只能单行显示;

ellipsize 用来指定TextView 的省略方式。这里使用marquee,也就是跑马灯的省略方式;

按道理来说,添加这两个属性应该就够了,为什么还要加上focusable 和focusableInTouchMode 这两个属性呢?我也并不非常明白,我认为是因为marquee的效果只有在当前控件获取焦点以后才有用,所以要添加focusable 和focusableInTouchMode来让TextView获取焦点。

这也能解释另外一个问题:当布局中有多个TextView的时候,只有第一个TextView能显示跑马灯的效果。想要解决这个问题,可以实现一个TextView的子类来继承TextView,重写其中的isFocused方法:

public class MyTextView extends TextView {

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

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

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

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

}

在这个子类里重写了父类所有的构造方法和isFocused 方法,让其返回true。也就是让两个所有的MyTextView 都获取焦点。
最后将布局中的TextView改成自定义的MyTextView

<com.example.marqueetextviewdemo.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:text="@string/hello_world" />

<com.example.marqueetextviewdemo.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:text="@string/hello_world" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android开发