Android 跑马灯效果的xml实现

最近买了本《Android Studio开发实战 从零基础到APP上线》的书,里面的第一个实例就是跑马灯效果,按照书上的代码写好了,可是执行起来却没有效果。

下面先把代码贴出来。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是一个跑马灯效果的文本试图,里面的文字太长了,具体多少我也不知道,此处略去十万字!!!"
        android:textColor="#00ff00"
        android:singleLine="true"
        android:scrollHorizontally="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true" />
   
</LinearLayout>

直接执行程序,发现一点反应都没有。教程中的例子是用下面这样的方式来实现的

if (v.getId() == R.id.tv_hello) {
            cpaust = !cpaust;
            if (cpaust){
                tv_hello.setFocusableInTouchMode(true);
                tv_hello.setFocusable(true);
            } else {
                tv_hello.setFocusable(false);
                tv_hello.setFocusableInTouchMode(false);
            }
        }

但是,这种方式来实现就失去了原有的意义了,试想一下,跑马灯肯定是页面一打开就开始滚动的,谁会设计成要去点击才能运行呢。

所以就找另一种方案解决,网上找了很多文章,都说是那几个属性设置一下就可以,结果都不行。最后找到一个,就是在activity中加一行 

tv_hello.setSelected(true);

就这么一行,效果马上就有了。

总结一下:

跑马灯的几个比较重要的属性:

 

 android:singleLine="true"    //必须是单行显示
 android:ellipsize="marquee"    //显示为跑马灯效果
 android:marqueeRepeatLimit="marquee_forever"    //设置滚动方式为永久滚动
 android:focusable="true"    //设置焦点
 android:focusableInTouchMode="true"    //设置触屏焦点

以上几个属性必须这样设置才行。还有一点,文字的长度必须要大于屏幕的长度才能滚动的起来。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值