Android, ¿Cómo limitar el ancho de TextView (y agregar tres puntos al final del texto)?


Tengo un TextView que quiero limitar los caracteres de la misma. En realidad, puedo hacer esto, pero lo que estoy buscando es cómo agregar tres puntos (...) al final de la cuerda. Este muestra que el texto ha continuado. Este es mi XML pero no hay puntos aunque limita mi texto.

<TextView 
        android:id                      = "@+id/tvFixture"
        android:layout_width            = "wrap_content"
        android:layout_height           = "wrap_content"
        android:layout_toLeftOf         = "@id/ivFixture_Guest"
        android:text                    = "@string/test_06"
        android:lines                   = "1"
        android:ems                     = "3"
        android:gravity                 = "right"
        style                           = "@style/simpletopic.black" 
        android:ellipsize="end"/>
Author: Niranj Patel, 2012-05-25

18 answers

En desuso:

Agregue una propiedad más android:singleLine="true" en su Textview

Actualizado:

android:ellipsize="end" 
android:maxLines="1"
 486
Author: Azhar Shaikh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-21 12:57:59

Lo siguiente es lo que aprendí jugando con varias opciones para forzar un TextView a una sola línea (con y sin los tres puntos).

introduzca la descripción de la imagen aquí

Android:maxLines="1"

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:text="one two three four five six seven eight nine ten" />

Esto solo fuerza el texto a una línea. Cualquier texto extra está oculto.

Relacionado:

Ellipsize = "end"

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:ellipsize="end"
    android:text="one two three four five six seven eight nine ten" />

Esto corta el texto que no encaja, pero permite a los usuarios saber que el texto ha sido truncado mediante la adición de puntos suspensivos (los tres puntos).

Relacionado:

Ellipsize = "marquesina"

<TextView
    android:id="@+id/MarqueeText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:text="one two three four five six seven eight nine ten" />

Esto hace el texto se desplaza automáticamente a través de TextView. Tenga en cuenta que a veces necesita ser establecido en código:

textView.setSelected(true);

Supuestamente android:maxLines="1" y android:singleLine="true"deberían hacer básicamente lo mismo y dado que singleLine es aparentemente obsoleto Preferiría no usarlo, pero cuando lo saco, la marquesina ya no se desplaza. Sin embargo, tomar maxLines no lo afecta.

Relacionado:

HorizontalScrollView con scrollHorizontally

<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/horizontalScrollView">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:scrollHorizontally="true"
        android:text="one two three four five six seven eight nine ten" />
</HorizontalScrollView>

Esto permite al usuario desplazarse manualmente para ver toda la línea de texto.

 130
Author: Suragch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:36

Pruebe esta propiedad de TextView en su archivo de diseño..

android:ellipsize="end"
android:maxLines="1"
 78
Author: Niranj Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-15 05:11:18

Entiendo que desea limitar el ancho a una línea y no limitarlo por carácter? Dado que singleLine está en desuso, puede intentar usar lo siguiente juntos:

android:maxLines="1"
android:scrollHorizontally="true"
android:ellipsize="end"
 29
Author: Muz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-06 10:46:55

Eg. puede usar

android:maxLength="13"

Esto restringirá la longitud de texview a 13, pero el problema es si intenta agregar 3 puntos(...), no lo mostrará, ya que será parte de la longitud de textview.

     String userName;
     if (data.length() >= 13) {
            userName = data.substring(0, 13)+ "...";

     } else {

            userName = data;

    }
        textView.setText(userName);

Aparte de esto tienes que usar

 android:maxLines="1"
 10
Author: Nayanesh Gupte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-16 06:24:42

Obtuve el resultado deseado usando

android:maxLines="2"
android:minLines="2"
android:ellipsize="end"

El truco es establecer líneas máximas y minLines al mismo valor... y no solo android: lines = "2", no hagas el truco. También está evitando cualquier atributo obsoleto.

 5
Author: user1974433,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-10 07:33:17

Código:

TextView your_text_view = (TextView) findViewById(R.id.your_id_textview);
your_text_view.setEllipsize(TextUtils.TruncateAt.END);

Xml:

android:maxLines = "5"

Por ejemplo

En Mateo 13, los discípulos le preguntaron a Jesús por qué les hablaba a las multitudes en parábolas. Él respondió: "A vosotros se os ha dado conocer los misterios del reino de los cielos, pero a ellos no se les ha dado.

Salida: En Mateo 13, los discípulos le preguntaron a Jesús por qué hablaba a las multitudes en parábolas. Él respondió: "Se te ha dado a saber...

 4
Author: richardj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-04 01:36:39

Puede limitar el número de caracteres de su textview y agregar (...) después del texto. Supongamos que necesita mostrar solo 5 letras y, a partir de entonces, debe mostrar (...), Solo haz lo siguiente :

String YourString = "abcdefghijk";

if(YourString.length()>5){

YourString  =  YourString.substring(0,4)+"...";

your_text_view.setText(YourString);
}else{

 your_text_view.setText(YourString); //Dont do any change

}

Un pequeño truco ^_^. Aunque no es una buena solución. Pero una obra en torno a la cual funcionó para mí :D

EDITAR: He añadido la comprobación de menos carácter según su número limitado. de personajes.

 4
Author: TheLittleNaruto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-01 09:17:38

Estoy usando Horizonal Recyclerview.
1) Aquí en CardView, TextView se distorsiona verticalmente cuando se usa

android:ellipsize="end"
android:maxLines="1"

Compruebe el TextViews negrita Wyman Group, Jaskolski... introduzca la descripción de la imagen aquí

2) Pero cuando usé singleLine junto con ellipsize -

android:ellipsize="end"
android:singleLine="true"

Compruebe el TextViews negrita Wyman Group, Jaskolski... introduzca la descripción de la imagen aquí

La 2a solución funcionó para mí correctamente (usando singleLine). También he probado en la versión del sistema operativo: 4.1 y superior (hasta 8.0), está funcionando bien sin ningún tipo de accidentes.

 4
Author: Varad Mondkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-18 11:15:32

Necesita agregar las siguientes líneas en su diseño para textview

android:maxLines="1"
android:ellipsize="end"
android:singleLine="true"

Espero que esto funcione para usted.

 3
Author: Mayank Bhatnagar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-01 09:22:24

Para trabajar con el atributo android:ellipsize, debe limitar el ancho de diseño del TextView, de modo que el text esté fuera de los límites de la vista de TextView.

Entonces, android:layout_width el atributo juega un papel clave aquí, establézcalo en consecuencia.

Un ejemplo puede ser:

<TextView        
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:text="This is a very long text to be displayed"
    android:textSize="12sp"
    android:maxLines="1"            
     />

Ahora, aquí si el text en android: text = "Este es un texto muy largo que se mostrará" sale de la vista desde TextView con un android:layout_width="120dp", android:ellipsize="final" truncará la texto y lugar ...(3 puntos) después de él. es decir, Esto es muy largo... se mostrará en la vista de texto.

 3
Author: Androwed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-05 09:31:40

Creo que le das altura fija y ancho de vista de texto. Entonces tu solución funcionará.

 2
Author: Vinay Kumar Baghel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-25 05:21:49

Puede escribir esta línea en xml donde toma el textview:

android:singleLine="true"
 2
Author: Jay Thakkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-19 16:22:28

Agregue estas dos líneas en su texto

android:ellipsize="end"
android:singleLine="true"
 1
Author: SANJAY GUPTA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-07 10:11:35

El enfoque de @AzharShaikh funciona bien.

android:ellipsize="end"
android:maxLines="1"

Pero me doy cuenta de un problema que TextView será truncado por word (por defecto). Mostrar si tenemos un texto como:

prueba long_line_without_any_space_abcdefgh

El TextView mostrará:

prueba...

Y encontré una solución para manejar este problema, reemplazar espacios con el carácter de espacio sin interrupción unicode, hace que TextView se ajuste a los caracteres en lugar de palabras:

yourString.replace(" ", "\u00A0");

El resultado:

prueba long_line_without_any_space_abc...

 1
Author: Think Twice Code Once,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-07 10:15:44

Usted acaba de cambiar

Android: layout_width= "wrap_content"

Utilice esta línea inferior

Android: layout_width = "match_parent"

<LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@+id/visitBox"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/txvrequestTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:text="Abcdefghighiklmnon"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="@color/orange_color" />


        </LinearLayout>
 0
Author: KeTaN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-15 13:53:05

Puedes hacer eso por xml:

<TextView 
    android:id="@+id/textview"
    android:maxLines="1" // or any number of lines you want
    android:ellipsize="end"
    />
 0
Author: Khalid Taha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-06 21:37:34

Use

  • android:singleLine="true"
  • android:maxLines="1"
  • app:layout_constrainedWidth="true"

Es como mi completo TextView se ve:

    <TextView
    android:id="@+id/message_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="5dp"
    android:maxLines="1"
    android:singleLine="true"
    android:text="NAME PLACEHOLDER MORE Text"
    android:textColor="@android:color/black"
    android:textSize="16sp"

    android:textStyle="bold"
    app:layout_constrainedWidth="true"
    app:layout_constraintEnd_toStartOf="@id/message_check_sign"
    app:layout_constraintHorizontal_bias="0"
    app:layout_constraintStart_toEndOf="@id/img_chat_contact"
    app:layout_constraintTop_toTopOf="@id/img_chat_contact" />

Imagen de TextView

 0
Author: kyrylo_23,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 23:36:02