Home > Blockchain >  How to settext on singleline TextView which length is over screen width
How to settext on singleline TextView which length is over screen width

Time:05-31

I have a TextView and want to show it with animation.

but when I set a text over screen width, it will be cut

How can I fix it.

enter image description here

Video Text is cut

  <TextView
        android:id="@ id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:background="#0000ff"
        android:lines="1"
        android:text="startmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmend"
        android:textColor="@color/white"
        android:textSize="20dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

How I animate it

val bounds = Rect()
viewBinding.textView.paint.getTextBounds(
    viewBinding.textView.text.toString(),
    0,
    viewBinding.textView.text.length, bounds)

viewBinding.textView
           .animate()
           .setInterpolator(LinearInterpolator())
           .x((screenWidth - bounds.width()).toFloat())
           .duration = 5000

CodePudding user response:

 <TextView
        android:id="@ id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:background="#0000ff"
        android:lines="1" // this
        android:text="startmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmend"

As you can see on your xml code, it provide max lines is 1, it will cut all view outside the scope of element view, Documentation. So for the solution you can make it inside horizontal scrollview then animate the scrollview for auto scrolling

CodePudding user response:

I finally solve the problem myself

Calculate the Text width and set the TextView width programmtically

    val defaultPadding = 50
    val bounds = Rect()
    val text = viewBinding.textView.text.toString()
    viewBinding.textView.paint.getTextBounds(text, 0, text.length, bounds)
    textView.layoutParams = ConstraintLayout.LayoutParams(
        bounds.width()   defaultPadding, LinearLayout.LayoutParams.WRAP_CONTENT
    )
    ConstraintSet().apply {
        clone(viewBinding.rootLayout)
        connect(R.id.textView, ConstraintSet.LEFT, R.id.rootLayout, ConstraintSet.LEFT, 0)
        connect(R.id.textView, ConstraintSet.RIGHT, R.id.rootLayout, ConstraintSet.RIGHT, 0)
        connect(R.id.textView, ConstraintSet.TOP, R.id.rootLayout, ConstraintSet.TOP, 350)
        applyTo(viewBinding.rootLayout)
    }
    viewBinding.textView
               .animate()
               .setInterpolator(LinearInterpolator())
               .x((screenWidth - bounds.width()-defaultPadding).toFloat())
               .duration = 5000

demo

  • Related