Cómo obtener N texto que se puede caber en la pantalla / TextView con un tamaño específico?
Tengo una gran historia en formato String. Quiero mostrar el texto en la galería. Lo que quiero hacer es cortar todo el texto de tal manera que toda mi vista en la galería muestre el texto que encaja en la pantalla.
Para que pueda hacer mi cuerda en parte, donde cada parte se mostrará en la pantalla y cada parte cubrirá toda la pantalla.
- ¿Cómo cambiar la fuente del cajón de navegación?
- La página Web Gujarati no se muestra perfecta en la vista Web
- Android: Problemas de renderización de fuentes con .ttf> 3 MB
- ¿Cómo mostrar el texto vectorizado usando libgdx?
- Presentación de texto de Android TextView vs WebView
Una cosa a tener en cuenta es que el usuario puede cambiar el tamaño del texto grande, pequeño para que el texto t en la pantalla también cambiará como cambio de tamaño.
Me pregunto si hay alguna manera de hacer esto. por favor, ayúdame
Solución
Muchas gracias por userSeven7s por ayudarme. Basado en su ejemplo soy capaz de hacer un ejemplo. Aquí está
package com.gsoft.measure.text; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.LinearLayout; import android.widget.TextView; public class MainScreen extends Activity { private final String TAG = "MainScreen"; private String textToBeShown = "These are the text"; private String sampleText = "Here are more text"; private TextView mTextView = null; Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == 1) { updateUI(); } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.ui_main_textView); mTextView.setTextSize(20f); for (int i = 0; i < 100; i++) { textToBeShown = textToBeShown + " =" + i + "= " + sampleText; } // I am using timer as the in UI is not created and // we can't get the width. TimerTask task = new TimerTask() { @Override public void run() { // So that UI thread can handle UI work handler.sendEmptyMessage(1); } }; Timer timer = new Timer(); timer.schedule(task, 1000 * 1); } @Override protected void onResume() { super.onResume(); } private void updateUI() { // Set text mTextView.setText(textToBeShown); // Check the width Log.e(TAG, "Width = " + mTextView.getWidth()); // Check height of one line Log.e(TAG, "Line height= " + mTextView.getLineHeight()); // Check total height for TextView Log.e(TAG, "Text height= " + mTextView.getHeight()); // No of line we can show in textview int totalLine = mTextView.getHeight() / mTextView.getLineHeight(); Log.e(TAG, "Total Lines are height= " + totalLine); for (int i = 0; i < totalLine; i++) { // Get No of characters fit in that textView int number = mTextView.getPaint().breakText(textToBeShown, 0, textToBeShown.length(), true, mTextView.getWidth(), null); Log.e(TAG, "Number of chracters = " + number); // Show the text that fit into line Log.e(TAG, textToBeShown.substring(0, number)); // Update the text to show next textToBeShown = textToBeShown.substring(number, textToBeShown.length()); } } }
Aquí está mi XML
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_id_for_value" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/black" android:orientation="vertical" > <TextView android:id="@+id/ui_main_textView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/twitter" android:textColor="@color/white" /> </LinearLayout>
- Libgdx en android no puede detectar fuentes GDX
- React Native: La personalización de la fuente se hace diferente en Android e iOS
- Uso de la fuente personalizada en Android TextView utilizando xml
- Fuente impresionante en la vista de lista de Android no funciona
- Establecer fuente personalizada en todas las TextViews
- Android: Desea establecer fuentes personalizadas para toda la aplicación no en tiempo de ejecución
- Tamaño de fuente de Android WebView en píxeles
- Cómo utilizar Roboto condesed (o fino) fuente en ICS +?
Comprobar el código fuente TextView
y ver cómo deciden dónde ellipsize la cadena.
El código para TextView
está aquí .
También puede utilizar el TextUtils
public static CharSequence ellipsize(CharSequence text, TextPaint p, float avail, TruncateAt where)
.
TextPaint p
debe ser el objeto de pintura de TextView.
Actualizar:
Otra alternativa es usar Paint.getTextWidths(char[] text, int index, int count, float[] widths)
.
textpaint.getTextWidths(char[] text, int index, int count, float[] widths); int i = 0; int prev_i = 0; while (i < count) { textWidth = 0; for (int i = prev_i; (i < count) || (textWidth < availableWidth); i++) { textWidth += widths[i]; } String textThatFits = mOriginalText.subString(prev_i, i); mTextview.setText(textThatFits); prev_i = i; }
i
es el número de caracteres que se ajustan en el TextView.
TextView
es el ancho del TextView
en píxeles.
Este código es aproximado y contiene errores de sintaxis. Tendrá que hacer algunos cambios menores para que funcione.
Actualización 2:
Otra alternativa sería utilizar
int breakText (CharSequence text, int start, int end, boolean measureForwards, float maxWidth, float[] measuredWidth).
Creo que esta es la mejor solución para usted. Consulte su documentación aquí.
Actualizar:
Ejemplo de código con la pintura. Método breakText
.
paint.setSubpixelText(true); int prevPos = 0; while (nextPos < chars.length) { int nextPos = paint.breakText(chars, prevPos, chars.length, maxWidth, null); tvStr = str.substring(prevPos, nextPos); prevPos = nextPos+1; }
Si cada parte tiene un número diferente de caracteres, también tendrá que tener diferentes tamaños de fuentes. No sólo eso, pero los dispositivos demasiado pequeños también tendrán un tamaño de fuente demasiado pequeño, ya que el texto debe encajar en un espacio más pequeño. Sugeriría tener el mismo tamaño de fuente para todas las piezas, mientras que permite desplazarse abajo si no hay bastante espacio.
Para ello, puede utilizar un viewpager con vistas de desplazamiento en cada página, cada uno contiene una vista de texto.
Graphics.getFontMetrics y FontMetrics.stringWidth le ayudarán a determinar el tamaño real del texto en la pantalla. Con base en este cálculo, puede determinar cuánto tiempo debe mostrarse la subcadena.