【Android】TextView水平滚动-跑马灯

作者:邹峰立,微博:zrunker,邮箱:[email protected],微信公众号:书客创作,个人平台:www.ibooker.cc。

本文选自书客创作平台第12篇文章。阅读原文 。

【Android】TextView水平滚动-跑马灯_第1张图片
书客创作

说到实现TextView文本水平滚动,大多数人首先会想到的是跑马灯,跑马灯实现起来比较容易,可以在布局文件中设置TextView属性实现。如:


注意要实现跑马灯效果必须要有三要素,否则无法实现:

1、跑马灯特效声明

  • android:ellipsize="marquee"

2、焦点

  • android:focusable="true"
  • android:focusableInTouchMode="true"

3、单行显示

  • android:singleLine="true"

除了这三要素之外,还有一个原则。

TextView上的文本长度要超过TextView的宽度,否则也无法实现跑马灯效果。

除了以上几个属性设置以外,还有几个额外的属性可以进行设置,如果不设置不影响跑马灯效果。

1、android:marqueeRepeatLimit="marquee_forever"// 一直循环跑(可以换成相应数字此时对应-1)。

2、android:scrollHorizontally="true"// 水平滚动。

这里存在一些弊端:如,在Android SDK高版本中,文本单行显示singleLine="true"属性过时,所以要使用maxLines="1"来代替,但是如果将singleLine="true"替换成maxLines="1",跑马灯将会失效。除此之外跑马灯特效还受焦点限制,当TextView失去焦点时,跑马灯也会失效。

对于焦点问题,可以采用重写TextView中的isFocused方法来实现。如:

public class MarqueeTextView extends android.support.v7.widget.AppCompatTextView {
    public MarqueeTextView(Context context) {
        super(context);
    }
    public MarqueeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public MarqueeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    // 焦点
    @Override
    public boolean isFocused() {
        return true;
    }
}

使用,在XML布局文件中添加如下代码即可:


到这里一个具有的跑马灯效果的TextView就实现了。最后给出工程引入方式,可以直接引入资源包到相应的工程中进行使用,这里给出两种引入方式:

1、在build.gradle文件中添加以下代码:

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}
dependencies {
    compile 'com.github.zrunker:ZTextView:v1.0.2'
}

2、在maven文件中添加以下代码:


    
        jitpack.io
        https://jitpack.io
    


    com.github.zrunker
    ZTextView
    v1.0.2

Github地址
阅读原文


【Android】TextView水平滚动-跑马灯_第2张图片
微信公众号:书客创作

你可能感兴趣的:(【Android】TextView水平滚动-跑马灯)