Android TextView实现跑马灯效果

来源:互联网 发布:iphone数据恢复软件 编辑:程序博客网 时间:2024/04/30 09:54

设置跑马灯效果相关属性:

1、*单行显示

android:singleLine="true"

2、*跑马灯效果设置

android:ellipsize="marquee"

3、*焦点设置

android:focusable="true"
android:focusableInTouchMode="true"

4、设置滚动次数,marquee_forever无限滚动

android:marqueeRepeatLimit="marquee_forever"

完整布局代码:

<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" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:singleLine="true"        android:ellipsize="marquee"        android:focusable="true"        android:focusableInTouchMode="true"        android:marqueeRepeatLimit="marquee_forever"        android:text="@string/hello_world" />   </LinearLayout>
这样跑马灯效果就实现了。但是如果现在布局中有两个TextView都想实现跑马灯效果,我们会将上面布局中的TextView复制一份粘到下面,这时运行会发现只有上面的有跑马灯效果,下面的依然没有。这是因为TextView默认是没有焦点的,在第一个获取到焦点后,第二个TestView就获取不到焦点,我们只要重写TextView控件,让其默认是获取焦点的状态就可以了。

1、自定义TextView,设置默认带有焦点。

package com.cx.texttest;import android.content.Context;import android.util.AttributeSet;import android.widget.TextView;public class MarqueeTextView extends TextView {public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);// TODO Auto-generated constructor stub}public MarqueeTextView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stub}public MarqueeTextView(Context context) {super(context);// TODO Auto-generated constructor stub}@Overridepublic boolean isFocused() {// TODO Auto-generated method stubreturn true;}}
2、布局文件
<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" >    <com.cx.texttest.MarqueeTextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:singleLine="true"        android:ellipsize="marquee"        android:marqueeRepeatLimit="marquee_forever"        android:text="@string/hello_world" />        <com.cx.texttest.MarqueeTextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:singleLine="true"        android:ellipsize="marquee"        android:marqueeRepeatLimit="marquee_forever"        android:text="@string/hello_world" /></LinearLayout>

0 0
原创粉丝点击