在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;
-
- 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代码中,就正常使用就行,不用再重新写获取焦点的代码了。