Android TextVIew 跑马灯

165 阅读1分钟

Android TextView 跑马灯效果可以通过设置TextView的marquee属性来实现。在xml中设置如下:

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="This is a marquee TextView This is a marquee TextView This is a marquee TextView This is a marquee TextView This is a marquee TextView This is a marquee TextView This is a marquee TextView This is a marquee TextView This is a marquee TextView This is a marquee TextView This is a marquee TextView"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever"
    android:focusable="true"
    android:focusableInTouchMode="true"/>

代码中实现可以通过以下方式:

TextView textView = findViewById(R.id.textView);
textView.setSelected(true);

要注意的点:

  1. 需要将TextView的singleLine属性设置为true,保证文字在一行显示。
  2. 需要将TextView的ellipsize属性设置为marquee,超出屏幕的文字会以省略号的形式显示。
  3. 需要将TextView的marqueeRepeatLimit属性设置为marquee_forever,保证文字不停的滚动。也可以设置为一定的次数。
  4. 需要将TextView设置为可获取焦点,保证跑马灯效果在TextView获取焦点时才会显示。可以在代码中设置focusable和focusableInTouchMode属性。
  5. 如果在展示的效果的时候发生了文字没有正常轮播而是在来回弹,可以在textView外部添加一层布局。