一、Android 实现两个TextView跑马灯效果

超长的文字在有限的布局中,实现一行循环显示?

如果是只有一个TextView实现跑马灯效果可以简单使用以下方式来实现:

 <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是一个Hello World!我是一个Hello World!我是一个Hello World!我是一个Hello World!"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:singleLine="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

这样简单的实现就可以显示跑马灯效果。

但是在实际的开发中,页面的布局往往比较复杂,如果显示两个跑马灯的文字,这种方法只能实现第一个,第二个不会出现效果。采用如下方法:

    首先我们写一个类,继承TextView这个类,实现它的构造方法,重写isFocused方法 ,将它的返回值都为true,

package com.example.administrator.marqueetextview;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by Administrator on 2018/3/8 0008.
 */

public class Marquee_Textview extends TextView {
    public Marquee_Textview(Context context) {
        super(context);
    }

    public Marquee_Textview(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public Marquee_Textview(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
   public boolean isFocused(){
        return true;
   }
}

在页面中将textView换成我们自己的TextView,两个textview就都可以实现跑马灯的效果了。

<com.example.administrator.marqueetextview.Marquee_Textview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是一个Hello World!我是一个Hello World!我是一个Hello World!我是一个Hello World!"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:singleLine="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.example.administrator.marqueetextview.Marquee_Textview
        android:layout_marginTop="50dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是一个Hello World!我是一个Hello World!我是一个Hello World!我是一个Hello World!"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:singleLine="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
实现原理:两个TextView,默认的是第一个获取焦点,第二个默认的是没有选中的。现在我们自己的TextView都是默认的强制的设置为被选中的状态的。





猜你喜欢

转载自blog.csdn.net/qq_38234785/article/details/79484789