每当想在界面上方底部插播跳循环滚动的通知或广告时,使用跑马灯效果来显示一条较长的文字是很不错的体验,主要用到的属性就是android:ellipsize="marquee"了:
<span style="white-space:pre"> </span><TextView
android:layout_centerInParent="true"
android:singleLine="true"
android:ellipsize="marquee"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Hello World!This is a very long long long long text" />
但这样用的伙伴都知道,这样并不会产生跑马灯这种循环滚动的效果,因为要想产生效果,就必须让textView获得焦点,于是就有了这种写法:
<span style="white-space:pre"> </span><TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:text="Hello World!This is a very long long long long text" />
通过添加 android:focusable="true" 和 android:focusableInTouchMode="true" 这两个属性就能产生正常的效果了,一般这样使用也没什么问题,然而在下面这种情况下:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true">
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:text="Hello World!This is a very long long long long text" />
</RelativeLayout>
又或是下面这种情况的按键被点击后:
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:text="Hello World!This is a very long long long long text" />
<Button
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是按钮" />
会发现跑马灯效果又没有了,textView 没有拿到焦点了,也就是说除了textView,其实还要检查其他控件会不会抢走你 textView 的焦点,这样感觉略烦,于是尝试用了另一个方法,自定义控件:
public class FocusedTextView extends TextView {
public FocusedTextView(Context context) {
super(context);
}
public FocusedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean isFocused() {
return true;
}
}
非常容易,就重写 isFocused() 方法,将返回值直接改成true就好了(不管我有没有真的获得焦点,你就当作我获得焦点就好了~),然后替换到布局里
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true">
<george.ni.variousnotificationdemo.widget.FocusedTextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:ellipsize="marquee"
android:singleLine="true"
android:text="Hello World!This is a very long long long long text" />
</RelativeLayout>
跑马灯效果就ok啦~