Deteniendo texto de división a varias líneas en los períodos en direcciones web

Tengo un Android TextView que muestra algún texto, y es multi-line. Sin embargo, en el texto, a veces tengo nombres de dominio; ¿Cómo puedo detener el TextView de dividir las líneas en los períodos en ellos?

¿Hay un unicode no-break-período, por ejemplo?


Para ver el problema en la acción de envolver una dirección de correo electrónico, ejecute
android create project --target 16 --path demo --package com.example.demo --activity MainActivity
Y cambie el texto en res/layout/main.xml a " Hello World, MyActivity filler text + email [email protected] ". Que produce esta salida en un Galaxy S3 (API nivel 16):

Envolvimiento del correo electrónico

(Ajustar el texto como sea apropiado para ver la envolvente en los dispositivos con otros tamaños de pantalla.Notably, el envoltorio se hace correctamente en la vista previa de diseño de Intellij, es sólo en el dispositivo que es defectuoso).

TLDR;

@Matt McMinn ya ha mostrado una solución para este problema aquí , ir a tomarlo. Sólo estoy repitiendo esa solución aquí.


Tenga en cuenta que este problema ya se ha solucionado a nivel de plataforma en Android 4.2.2. Vea las siguientes capturas de pantalla para la comparación de palabras para la misma base de código pero diferentes versiones de plataforma en Galaxy Nexus.

Comparación de palabras en Android 4.1.2 vs Android 4.2.2

Por lo tanto, si no está apuntando a versiones anteriores de Android, es posible que no desee utilizar esta corrección en absoluto.

El código

MainActivity.java :

 package com.example.nobr; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.widget.TextView.BufferType; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView helloWorld = (TextView) findViewById(R.id.hello_world); helloWorld.setText(R.string.hello_world, BufferType.EDITABLE); TextView longText = (TextView) findViewById(R.id.long_text); longText.setText(R.string.long_text_with_url, BufferType.EDITABLE); } } 

Activity_main.xml :

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" > <com.example.nobr.NonBreakingPeriodTextView android:id="@+id/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <com.example.nobr.NonBreakingPeriodTextView android:id="@+id/long_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/hello_world" android:layout_below="@+id/hello_world" android:layout_marginTop="20dp" /> </RelativeLayout> 

NonBreakingPeriodTextView.java :

 package com.example.nobr; import android.content.Context; import android.graphics.Paint; import android.text.Editable; import android.util.AttributeSet; import android.util.Log; import android.widget.TextView; public class NonBreakingPeriodTextView extends TextView { private static final String TAG = "NonBreakingPeriodTextView"; public NonBreakingPeriodTextView(Context context) { super(context); } public NonBreakingPeriodTextView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { Editable editable = getEditableText(); if (editable == null) { Log.d(TAG, "non-editable text"); return; } int width = getWidth() - getPaddingLeft() - getPaddingRight(); if (width == 0) { Log.d(TAG, "zero-length text"); return; } Paint p = getPaint(); float[] widths = new float[editable.length()]; p.getTextWidths(editable.toString(), widths); float curWidth = 0.0f; int lastWSPos = -1; int strPos = 0; final char newLine = '\n'; final String newLineStr = "\n"; boolean reset = false; int insertCount = 0; /* * Traverse the string from the start position, adding each character's width to the total * until: 1) A whitespace character is found. In this case, mark the whitespace position. If * the width goes over the max, this is where the newline will be inserted. 2) A newline * character is found. This resets the curWidth counter. curWidth > width. Replace the * whitespace with a newline and reset the counter. */ while (strPos < editable.length()) { curWidth += widths[strPos]; char curChar = editable.charAt(strPos); if (curChar == newLine) { reset = true; } else if (Character.isWhitespace(curChar)) { lastWSPos = strPos; } else if (curWidth > width && lastWSPos >= 0) { editable.replace(lastWSPos, lastWSPos + 1, newLineStr); insertCount++; strPos = lastWSPos; lastWSPos = -1; reset = true; } if (reset) { curWidth = 0.0f; reset = false; } strPos++; } if (insertCount != 0) { setText(editable); } } } 

El resultado

En Android 4.1.2 (Galaxy Nexus)

Word wrap en Android 4.1.2 con la corrección

En Android 2.3.3 (AVD, clon de Nexus One)

Introduzca aquí la descripción de la imagen

Espero que esto ayude.

Para indicarle a android que analiza los enlaces de dominio en el TextView utilice este código en el bloque de código TextView:

 android:autoLink="web" 

Esto mostrará los nombres de dominio como enlaces en la aplicación y no dividirá las líneas.

Utilizar esta :

Android: singleLine = "true" en xml

Para mí no funcionó la solución de @ozbek respectivamente @Matt McMinn, tuve que cambiar de línea

 else if(Character.isWhitespace(curChar)) 

para

 } else if (curChar == '\u00A0') { 

Pero por lo demás gran solución, gracias

  • Diferentes idiomas en la vista de texto en Android
  • Android TextView measureText para el árabe
  • Proteger la aplicación de la descompilación ocultando Manifest y convirtiendo el código en un carácter Unicode
  • SMS en hebreo en Android
  • Cómo mostrar Emoticons / Emoji en Snackbar o Toast / Textview
  • Cómo enviar caracteres unicode en un HttpPost en Android
  • Recibe todos los caracteres unicode de SoftInput cuando usa android NativeActivity
  • Cómo establecer emoji por unicode en android textview
  • Creación de softkey con emoji personalizado
  • Soporte unicode en android ndk
  • Mostrar icono de emoji / emoción en Android TextView
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.