Estoy tratando de crear un método para cambiar el tamaño del texto de varias líneas de tal manera que encaje dentro de los límites (tanto las dimensiones X como Y) del archivo .TextView
TextView
En la actualidad, tengo algo, pero todo lo que hace es cambiar el tamaño del texto de tal manera que solo la primera letra / carácter del texto llene las dimensiones del (es decir, solo la primera letra es visible y es enorme). Necesito que se ajuste a todas las líneas del texto dentro de los límites de TextView.TextView
Esto es lo que tengo hasta ahora:
public static void autoScaleTextViewTextToHeight(TextView tv)
{
final float initSize = tv.getTextSize();
//get the width of the view's back image (unscaled)....
float minViewHeight;
if(tv.getBackground()!=null)
{
minViewHeight = tv.getBackground().getIntrinsicHeight();
}
else
{
minViewHeight = 10f;//some min.
}
final float maxViewHeight = tv.getHeight() - (tv.getPaddingBottom()+tv.getPaddingTop())-12;// -12 just to be sure
final String s = tv.getText().toString();
//System.out.println(""+tv.getPaddingTop()+"/"+tv.getPaddingBottom());
if(minViewHeight >0 && maxViewHeight >2)
{
Rect currentBounds = new Rect();
tv.getPaint().getTextBounds(s, 0, s.length(), currentBounds);
//System.out.println(""+initSize);
//System.out.println(""+maxViewHeight);
//System.out.println(""+(currentBounds.height()));
float resultingSize = 1;
while(currentBounds.height() < maxViewHeight)
{
resultingSize ++;
tv.setTextSize(resultingSize);
tv.getPaint().getTextBounds(s, 0, s.length(), currentBounds);
//System.out.println(""+(currentBounds.height()+tv.getPaddingBottom()+tv.getPaddingTop()));
//System.out.println("Resulting: "+resultingSize);
}
if(currentBounds.height()>=maxViewHeight)
{
//just to be sure, reduce the value
tv.setTextSize(resultingSize-1);
}
}
}
Creo que el problema está en el uso de . Siempre devuelve números pequeños para los límites del texto… pequeño en relación con el y los valores… incluso si el tamaño del texto es mucho mayor que el ancho o alto del archivo .tv.getPaint().getTextBounds(...)
tv.getWidth()
tv.getHeight()
TextView
Solución
La biblioteca AutofitTextView de MavenCentral maneja esto muy bien. La fuente alojada en Github (1k + estrellas) en https://github.com/grantland/android-autofittextview
Agregue lo siguiente a su app/build.gradle
repositories {
mavenCentral()
}
dependencies {
implementation 'me.grantland:autofittextview:0.2.+'
}
Habilite cualquier vista que extienda TextView en código:
AutofitHelper.create(textView);
Habilite cualquier vista que extienda TextView en XML:
<me.grantland.widget.AutofitLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
/>
</me.grantland.widget.AutofitLayout>
Utilice el widget integrado en código o XML:
<me.grantland.widget.AutofitTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
/>
Otras respuestas
He jugado con esto durante bastante tiempo, tratando de obtener mis tamaños de fuente correctos en una amplia variedad de tabletas de 7 «(kindle fire, Nexus7 y algunas económicas en China con pantallas de baja resolución) y dispositivos.
El enfoque que finalmente funcionó para mí es el siguiente. El «32» es un factor arbitrario que básicamente da más de 70 caracteres a través de una línea horizontal de tableta de 7″, que es un tamaño de fuente que estaba buscando. Ajuste en consecuencia.
textView.setTextSize(getFontSize(activity));
public static int getFontSize (Activity activity) {
DisplayMetrics dMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
// lets try to get them back a font size realtive to the pixel width of the screen
final float WIDE = activity.getResources().getDisplayMetrics().widthPixels;
int valueWide = (int)(WIDE / 32.0f / (dMetrics.scaledDensity));
return valueWide;
}