Android-TextView跑马灯效果实现与分析

在阅读博客的时候看到有关于TextView跑马灯的效果,感觉是一个不错的效果,平常在开发中也很容易用到。于是就简单的实现了一次跑马灯的效果。
首先,实现跑马灯效果的主要是用到TextView中的一个属性:

android:ellipsize
If set, causes words that are longer than the view is wide to be ellipsized instead of broken in the middle. You will often also want to set scrollHorizontally or singleLine as well so that the text as a whole is also constrained to a single line instead of still allowed to be broken onto multiple lines.
从文档中的解释来看,大概意思就是:如果设置了ellpsize这个属相,那么当文本的长度比视图宽时,不会从中间破坏词语。除了这个属性外,还需要设置
scrollHorizontally或者singleLine这些属性来把文本限制在一行。
在开发中也会注意到如果没有singleLine这个属性为true的话,那么超出视图长度的文本将会以多行的形式显示。
android:ellipsize有5种值,即:
none-0, start-1, middle-2, end-3, marquee-4
其中marquee就是实现跑马灯需要设置的属性值。而none表示不设置,其它的3种值时当文本长度超出时省略号的显示位置。

说完这些跑马灯的效果也就很轻松就实现了。

<TextView
        android:id="@+id/my_text1"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:text="I am the king of North"/>

所以上面的这段代码就是跑马灯的所有实现配置。
除了刚才讲的几点,是不是还发现了这两点
android:focusable=”true”
android:focusableInTouchMode=”true”
当不设置这两点为true时,跑马灯便不能实现,这是为什呢,因为实现跑马灯的TextView需要保持有焦点。于是我就看了TextView的源码,在里面找到了原因。在onDraw()函数中我看到了一个函数是restartMarqueeIfNeeded();一步步的看下去就找到了这段代码。从代码里不难看出当要实现跑马灯时,这些条件都要有:
mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&getLineCount() == 1 && canMarquee()
这也就解释了为什么要设置singleLine和focusable了。

private void startMarquee() {
        // Do not ellipsize EditText
        if (getKeyListener() != null) return;

        if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
            return;
        }

        if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&
                getLineCount() == 1 && canMarquee()) {

            if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
                mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_FADE;
                final Layout tmp = mLayout;
                mLayout = mSavedMarqueeModeLayout;
                mSavedMarqueeModeLayout = tmp;
                setHorizontalFadingEdgeEnabled(true);
                requestLayout();
                invalidate();
            }

            if (mMarquee == null) mMarquee = new Marquee(this);
            mMarquee.start(mMarqueeRepeatLimit);
        }
    }

至此跑马灯效果就完成了,这个效果实现起来不难,主要处理一下焦点的问题就好。在网上还看到一种解决方案,就是通过自定义TextView来重写里面返回焦点状态的函数,只要一致返回true就可以解决焦点问题。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值