文章

文字跑马灯

文字跑马灯

TextView 文字跑马灯

TextView 跑马灯(显示一行,滚动显示)

TextView 不会主动获取焦点,一个布局中只能有一个组件获取焦点
获取到焦点时跑马灯。
设置成 maxLines=”1” 时跑马灯不工作,要用 singleLine=”true”

系统自带的 xml 中进行属性配置

1
2
3
4
android:ellipsize="marquee"  
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"  //只显示一行

自定义一个滚动的 TextView

对 button,这种,可以触摸获取焦点的,配置 android:ellipsize=”marquee” android:singleLine=”true”  ,就可以将看不到的文字显示出来,而 TextView,天生不能获取焦点,那只能重写里面的方法,isActivated (),让其返回 true,那么就可以被获取焦点了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class FocusedTextView extends AppCompatTextView {
    public FocusedTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

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

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

控制跑马灯

1
2
3
4
5
6
7
btn_start_marquee.setOnClickListener {
    if (tv_marquee.getEllipsize() != null) {
        tv_marquee.setEllipsize(null);
    } else {
        tv_marquee.setEllipsize(TextUtils.TruncateAt.MARQUEE);
    }
}

跑马灯控制方向

本文由作者按照 CC BY 4.0 进行授权