TextView跑马灯效果的两种实现方法

来源:互联网 发布:建筑效果图软件 编辑:程序博客网 时间:2024/04/28 03:14

网上还有其他的方法来实现,这里我只简单介绍两种我自己用的方法。由于跑马灯效果必须要在获得焦点的情况下才能正确显示,所以下面的方法都是围绕如何获得焦点来进行的。

第一种:通过xml布局文件的方式来实现,下面是具体代码

    <TextView        android:id="@+id/tv_ad"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="5dp"        android:ellipsize="marquee"        android:focusable="true"        android:focusableInTouchMode="true"        android:singleLine="true"        android:text="测试滚动文字123456789测试滚动文字123456789测试滚动文字123456789测试滚动文字123456789"/>

主要是这三个参数android:ellipsize=”marquee”        android:focusable=”true”        android:focusableInTouchMode=”true”,另外需要设置单行显示才可以。

第二种:通过自定义控件的方式重写TextView的方法,来强制设置焦点

创建一个类,继承并实现TextView的默认构造方法,然后重写父类的isFocused方法,强制输出true,代码如下

public class FocusedTextView extends TextView {    /**     * 这个构造方法是在用代码new的时候调用     */    public FocusedTextView(Context context) {        super(context);    }    /**     * 这个构造方法是有属性的时候调用     */    public FocusedTextView(Context context, AttributeSet attrs) {        super(context, attrs);    }    /**     * 这个构造方法是有style样式的时候调用     */    public FocusedTextView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    /**     * 强制设置焦点     */    @Override    public boolean isFocused() {        return true;    }}

然后在布局文件当中使用这个自定义控件

    <com.xxxlu.top.view.FocusedTextView    android:id="@+id/tv_ad"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:singleLine="true"    android:layout_marginTop="5dp"    android:ellipsize="marquee"    android:text="测试滚动文字123456789测试滚动文字123456789测试滚动文字123456789测试滚动文字123456789"/>

至此就可以正确显示了。

上面两种方法各有自己的特点,可以根据自己的项目需要灵活使用。

星星小路,版权所有丨转载请注明转自:http://xxxlu.top/archives/191
0 0
原创粉丝点击