Android 跑马灯效果auto scroll textview简化设置和解决焦点获取问题

在Android中TextView要实现跑马灯的效果,一般都是在xml文件中给TextView设置以下配置:

android:ellipsize="marquee" 
android:focusable="true" 
android:marqueeRepeatLimit="marquee_forever" 
android:focusableInTouchMode="true" 
android:scrollHorizontally="true"
android:singleLine="true"

然后在java代码中,设置时,需要加上requestFocus方法,这样配置特别麻烦,而且在某些机型中,就算按照这样设置,如果在设置了文字之后,再改变文字的内容,或者期间做了其他操作,发现跑马灯效果失效了,没有再自动滚动。


所以我重写了一个TextView,简化了配置,并且解决了失效的问题。

代码如下:


import android.content.Context;
import android.graphics.Rect;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 跑马灯效果TextView,简化了跑马灯的设置,解决某些机型焦点获取问题
 * 创建时间:2015-8-26 上午10:32:11
 * @author Miaozz.
 *
 */
public class ScrollingTextView extends TextView {

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

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

	public ScrollingTextView(Context context) {
		super(context);
		init();
	}

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

	@Override
	public void onWindowFocusChanged(boolean focused) {
		if (focused)
			super.onWindowFocusChanged(focused);
	}

	@Override
	public boolean isFocused() {
		return true;
	}

	private void init() {
		setEllipsize(TruncateAt.MARQUEE);// 对应android:ellipsize="marquee"
		setMarqueeRepeatLimit(-1);// 对应android:marqueeRepeatLimit="marquee_forever"
		setSingleLine();// 等价于setSingleLine(true)
	}
}

在xml中,只需在xml文件中进行如下配置:
<com.demo.view.ScrollingTextView
	android:id="@+id/tv_name"
	android:layout_width="800px"
	android:layout_height="wrap_content"
/>

在java代码中,就正常使用就行,不用再重新写获取焦点的代码了。





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值