Android控件TextView的跑马灯效果

只有一个需要实现跑马灯效果的TextVIew

在xml布局文件中加入一个TextView控件

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:text="这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本" />

注意其中的ellipsize、singleLine、focusable、focusableInTouchMode三个属性。

android:singleLine ——设置单行显示。如果和layout_width一起使用,当文本不能全部显示时,后面用“…”来表示。如android:text=”test_ singleLine “android:singleLine=”true”android:layout_width=”20dp”将只显示“t…”。如果不设置singleLine或者设置为false,文本将自动换行

android:ellipsize——设置当文字过长时,该控件该如何显示。有如下值设置:”start”—–省略号显示在开头;”end”——省略号显示在结尾;”middle”—-省略号显示在中间;”marquee” ——以跑马灯的方式显示(动画横向移动)

android:focusable——view是否具有接受焦点的资格

android:focusableInTouchMode——对应在触摸模式下,view是否具有焦点的资格

有多个需要实现跑马灯效果的TextView

如果直接按照上面的xml布局复制一个TextView,第二个TextView会出现无法获得焦点,从而不会出现跑马灯效果的情况。
所以我们需要新建一个类继承自TextView,通过Override Isfocused()方法来使第二个textview也获得焦点。

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

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

    public MarqueeText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

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

记得将xml的TextVIew修改为包中的Marquee,之后可以不写focusable和focusableInTouchMode两个属性

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="lqy.marquee_demo.MainActivity">

    <lqy.marquee_demo.MarqueeText
        android:id="@+id/marqueetext1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:text="这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本" />

    <lqy.marquee_demo.MarqueeText
        android:id="@+id/marqueetext2"
        android:layout_below="@+id/marqueetext1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:text="这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本 这是一个很长很长很长很长很长的文本" />

</RelativeLayout>

写好的跑马灯链接https://github.com/tjliqy/Marquee_Demo.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值