Android ListView/GridView 等控件使用文字跑马灯效果

TextView自带有跑马灯效果, 但是在特殊场景下使用时会出现跑马灯效果失效的问题。如ListView / GridView等适配器控件使用时。

TextView设置跑马灯效果有两种方式:

TextView tv = new TextView(getContext());
tv.setSingleLine(true);
tv.setEllipsize(TextUtils.TruncateAt.MARQUEE);
<TextView 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:singleLine="true"
    android:focusable="true"
    android:ellipsize="marquee"
    android:focusableInTouchMode="true"
    android:marqueeRepeatLimit="marquee_forever"/>
<!-- 
    造成无法正常显示跑马灯效果的原因有:
    1). 当前TextView无焦点, 只有当前View获取到焦点才会有跑马灯效果。
    2). android:marqueeRepeatLimit属性设置不正确, 该属性设置跑马灯效果循环次数。
-->

TextView和ListView配合使用时因为有很多的Adapter Item。当前TextView不一定有焦点, 即便有焦点也只有一个TextView会有跑马灯动画。没错, 原因就是因为TextView没有焦点。

那么如下思路可能会帮助你解决问题。

 public class MarqueeTextView extends TextView {

    public MarqueeTextView(Context context) {
        super(context);
    }

    public MarqueeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(true);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(true, direction, previouslyFocusedRect);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值