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"    //设置触屏焦点

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章