android marquee textview 走马灯效果

网上查的全都不能用。还是自己试验出来的。。。

测试机版本:4.0.3

网上有文章说要加 addStatesFromChildren

实测:加不加都能正常滚动

android:focusable="true"

实测:必须在xml里添加。在程序中使用tv.setFocusable(true);不能滚动

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:addStatesFromChildren="true"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:singleLine="true"
        android:text="11adshfkalhafklajfhkadjfhakjfhdjkfhadfjkhasdfhasdfjkhashkadjfhakjfhdjkfhadfjkhasdfhasdfjkhashkadjfhakjfhdjkfhadfjkhasdfhasdfjkhashkadjfhakjfhdjkfhadfjkhasdfhasdfjkhashkadjfhakjfhdjkfhadfjkhasdfhasdfjkhasdjkfhsdakfhasdjkfhasdkfhsajkdfhsdfhsadfkjhsaf" />

    <Button
        android:id="@+id/xinle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sad" />

</LinearLayout>

 点击button可以切换模式

findViewById(R.id.xinle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag = !flag;
                if (flag) {
                    textView.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
                    return;
                }
                textView.setEllipsize(TextUtils.TruncateAt.valueOf("MARQUEE"));
            }
        });

关于ellipsize这个参数的用法

在xml中

android:ellipsize = "end"    省略号在结尾

android:ellipsize = "start"   省略号在开头

android:ellipsize = "middle"     省略号在中间

android:ellipsize = "marquee"  跑马灯

最好加一个约束android:singleline = "true"

当然也可以用代码语句

tv.setEllipsize(TextUtils.TruncateAt.valueOf("END"));

tv.setEllipsize(TextUtils.TruncateAt.valueOf("START"));

tv.setEllipsize(TextUtils.TruncateAt.valueOf("MIDDLE"));

tv.setEllipsize(TextUtils.TruncateAt.valueOf("MARQUEE"));

最好再加一个约束tv.setSingleLine(true);

原文地址:https://www.cnblogs.com/622698abc/p/3833550.html