SoFunction
Updated on 2025-04-08

Example of Android using TextView to achieve marquee effect

I've encountered this problem before, and I picked it up again today.

The marquee effect is actually when the text exceeds the width of the TextView control and displays it in scrolling:

Method 1: (Do it directly with xml)

In Android system, TextView must meet the following conditions:

1、android:ellipsize=”marquee”;

2. The TextView must be displayed in a single line, and the content must exceed the width of the TextView;

3. The TextView needs to get focus before it can scroll.

The xml code is as follows:

  <TextView
   android:
   android:layout_width="20dp"
   android:padding="@dimen/space_4"
   android:layout_height="wrap_content"
   app:layout_rowWeight="2"
   app:layout_columnWeight="2"
   android:text="0"
   android:ellipsize="marquee"
   android:focusableInTouchMode="true"
   android:singleLine="true"
   android:focusable="true"/>

Among them: the ellipsize property refers to the display method when the text length exceeds the length of the TextView. The specific parameters are

**Android:ellipsize=”start”——The ellipsize is displayed at the beginning “…pedia”

android:ellipsize=”end”——the ellipsize is displayed at the end “encyc…”

android:ellipsize=”middle”——The ellipsize is displayed in the middle “en…dia”

android:ellipsize=”marquee” – displayed in horizontal scrolling mode (when you need to get the current focus)**

Method 2 (custom control)

I saw that my previous implementation method was like this. Maybe the first method is not suitable for the lower version of the platform. If the requirements are not met, you can try this method.

 

package ;

import ;
import ;
import ;

/**
  * @author Writer: xiaox
  * @date Created time: 2017/1/10
  * @Description Function description: This class
  */

public class TextViewSlide extends TextView {
 public TextViewSlide(Context context) {
  super(context);
 }

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

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

activity_main.xml 

 <
  android:
  android:layout_width="@dimen/item_width"
  android:layout_height="wrap_content"
  android:gravity="center_horizontal"
  android:layout_gravity="center_vertical"
  android:layout_weight="1"
  android:padding="8dp"
  android:marqueeRepeatLimit="marquee_forever"
  android:ellipsize="marquee"
  android:scrollHorizontally="true"
  android:focusableInTouchMode="true"
  android:singleLine="true"
  tool:text="asda" />

You can see that the second way is to get the focus of the control in the custom control. It feels no difference from the first one.

Currently, there is no problem in experimenting on both methods on android7.1.1 and android4.4.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.