Search code examples
androidandroid-layouttextviewmarquee

Marque text not moving if texts are less in android


I am using below code, it's working fine for big statement, but not for small text like only "hello".

<TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit="marquee_forever"
            android:maxLines="1"
            android:scrollHorizontally="true"
            android:singleLine="true"
            android:text="this_bill_has_some_unipay_points_promotion"/>

Solution

  • You should call TextView.isSelected = true to start the text moving.

    Edit: Working solution

    <TextView
         android:id="@+id/textView"
         android:layout_width="match_parent"             
         android:layout_height="48dp"
         android:ellipsize="marquee"
         android:gravity="center_vertical"
         android:scrollHorizontally="true"
         android:singleLine="true"
         android:textColor="@android:color/white" />
    

    Extension function

    fun TextView.setMovingText(text: String) = this.post {
                val textWidth = this.paint.measureText(text)
                val spaceWidth = this.paint.measureText(" ")
                val requiredAdditionalSpace = ((this.width - textWidth) / spaceWidth).toInt()
                this.text = StringBuilder(text).apply {
                    for (i in 0..requiredAdditionalSpace) {
                        append(" ")
                    }
                }
                this.isSelected = true
            }
    

    How to use

    textView.setMovingText("Hey")
    

    I just wanted to show a working solution. Also you can (should) modify for better performance and check for negative values.