Android TextView 跑马灯效果的实现
<TextView android:layout_width="100px"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:ellipsize="marquee"
android:focusable="true"
android:singleLine="true"
android:marqueeRepeatLimit="marquee_forever"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:text="。。。。。。。。。。。。。。。。。"
>
</TextView>
对于TextView这个控件来说,他的默认的Clickable,LongClickable,Focusable,FocusableInTouchMode这四个属性的值都是false,所以跑马灯效果也就不会出来,所以我们跑马灯效果需要TextVIew获得当前的焦点(focus)
所以我们需要
android:focusable="true"
但是,其实只有这个也是不行的
如果这两个属性设置成android:focusable="true"以及android:focusableInTouchMode="false",那么会发现程序运行之后,走马灯效果没有出现,这个时候需要用户按下手机或者模拟器上的上下导航键,才能让走马灯的效果出现,这说明android:focusable是针对于手机按键有效的,然而根据api的解释,
android:focusableInTouchMode是根据屏幕触摸决定的。
2.
如果这两个属性设置成android:focusable="false"与android:focusableInTouchMode="true",那么无论如何走马灯都出现不了了,就算加上android:clickable="true"也不行,这说明 android:focusable="true"是android:focusableInTouchMode="true"能有效的先决条件,我推测可能是在源码实现中,android:focusableInTouchMode逻辑是嵌套在android:focusable中的,
3.
在把这两个属性都设置成true以后,会发现程序运行之后,走马灯效果自动就显现了出来,这说明应用在运行后,会自动地按照某种顺序(在这里应该是自上而下),寻找第一个android:focusableInTouchMode="true"这个属性有效的第一个控件,当然要使这个属性有效按照前面的讨论android:focusable="true"也必须具备。根据测试,LinearLayout的Clickable,LongClickable,Focusable,FocusableInTouchMode这四个属性默认也都是false,因此,在上面的例子中TextView就率先获得了焦点,
走马灯也就走了起来了。
二、
宽度android:layout_width不可以设置为wrap_content(自适应内容)
android:text最少要长过自己设置的width大小
颜色最好别设置为@android:color/white,否则你什么都看不到,因为背景颜色也是white
三、
android:elipsize这里我们强调一下所谓跑马灯效果不过是elipsize(省略)的扩展(显示给定长度内无法显示的文字)
所以这也对应了我们第三点提到的android:text最少要长过自己设置的width大小
android:ellipsize = "end" 省略号在结尾
android:ellipsize = "start" 省略号在开头
android:ellipsize = "middle" 省略号在中间
android:ellipsize = "marquee" 跑马灯
四、
android:scrollHorizontally="true"相信大家英文水平还不错的话都明白这句的意思是水平滚动
android:marqueeRepeatLimit="marquee_forever" 看英文同样可以明白,是无限次循环,学习android,英文基础还是必须的。