Android TextView实现跑马灯

TextView实现跑马灯的效果:
例子一:

这个例子可以解决给一个TextView实现跑马灯的效果,但是不能解决给所有的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="这个项目的作用就是让这个单行的很长很长的单独一行的TextView实现跑马灯的效果。。。。。。" />

但是这种方法在有两个TextView的时候不能给两个TextView同时实现跑马灯的效果。
原因是:TextView默认的isFocused()方法默认只能给一个对象实现focused。
解决的办法是新建一个类MarqueeTextView继承TextView,让他的isFocused()方法返回true。(注意:子类MarqueeTextView需要实现父类的所有3个构造函数,不然会有问题)。

package com.example.textviewhorseracelamp;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class MarqueeTextView extends TextView {
    
    
    public MarqueeTextView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

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

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

    @Override
    public boolean isFocused() {
        return true;
    }
}
MarqueeTextView.java
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <com.example.textviewhorseracelamp.MarqueeTextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:text="这个项目的作用就是让这个单行的很长很长的单独一行的TextView实现跑马灯的效果。。。。。。" />
    
    <com.example.textviewhorseracelamp.MarqueeTextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:text="这个项目的作用就是让这个单行的很长很长的单独一行的TextView实现跑马灯的效果。。。。。。" />

</RelativeLayout>
activity_main.xml

效果:

补充:像素
 px不能根据分辨率进行缩放
 dp,sp,dip可以根据分辨率进行缩放显示(现在以dp作为标准)
 sp更多的用在文字的缩放
  
  

原文地址:https://www.cnblogs.com/moonlightpoet/p/5401095.html