TextView实现文字滚动需要以下几个要点:
1.文字长度长于可显示范围:android:singleLine="true"
2.设置可滚到,或显示样式:android:ellipsize="marquee"
3.自定义滚动的ScrollingTextView
1 public class ScrollingTextView extends TextView { 2 3 public ScrollingTextView(Context context, AttributeSet attrs, int defStyle) { 4 super(context, attrs, defStyle); 5 } 6 7 public ScrollingTextView(Context context, AttributeSet attrs) { 8 super(context, attrs); 9 } 10 11 public ScrollingTextView(Context context) { 12 super(context); 13 } 14 15 @Override 16 protected void onFocusChanged(boolean focused, int direction, 17 Rect previouslyFocusedRect) { 18 if (focused) 19 super.onFocusChanged(focused, direction, previouslyFocusedRect); 20 } 21 22 @Override 23 public void onWindowFocusChanged(boolean focused) { 24 if (focused) 25 super.onWindowFocusChanged(focused); 26 } 27 28 @Override 29 public boolean isFocused() { 30 return true; 31 } 32 33 }
在布局里调用自定义的TextView:
1 <com.example.rolltextdemo.ScrollingTextView 2 android:id="@+id/textview" 3 android:layout_width="wrap_content" 4 android:layout_height="wrap_content" 5 android:ellipsize="marquee" 6 android:marqueeRepeatLimit="marquee_forever" 7 android:singleLine="true" 8 android:text="@string/hello_world" />