Aplicar dos estilos de fuente diferentes a un TextView

Quiero aplicar dos estilos de fuente diferentes a un texto en un único TextView.

Mi caso es el mismo que Android – dos frases, dos estilos, un TextView . La única diferencia es que quiero configurar una fuente personalizada en todo el texto. He incluido Helvetica Font como un activo en mi proyecto y quiero aplicar esa fuente a la TextView con la primera parte del texto será Helvetica BOLD y parte restante Helvetica NORMAL. ¿Alguna sugerencia de cómo se puede hacer?

Texto necesario en el siguiente formato. Texto de encargo con diversos estilos y solo textview.

Introduzca aquí la descripción de la imagen

Una forma de hacerlo es extender TypefaceSpan :

import android.graphics.Paint; import android.graphics.Typeface; import android.text.TextPaint; import android.text.style.TypefaceSpan; public class CustomTypefaceSpan extends TypefaceSpan { private final Typeface newType; public CustomTypefaceSpan(String family, Typeface type) { super(family); newType = type; } @Override public void updateDrawState(TextPaint ds) { applyCustomTypeFace(ds, newType); } @Override public void updateMeasureState(TextPaint paint) { applyCustomTypeFace(paint, newType); } private static void applyCustomTypeFace(Paint paint, Typeface tf) { int oldStyle; Typeface old = paint.getTypeface(); if (old == null) { oldStyle = 0; } else { oldStyle = old.getStyle(); } int fake = oldStyle & ~tf.getStyle(); if ((fake & Typeface.BOLD) != 0) { paint.setFakeBoldText(true); } if ((fake & Typeface.ITALIC) != 0) { paint.setTextSkewX(-0.25f); } paint.setTypeface(tf); } } 

A continuación, cuando desee utilizar dos tipos de letra diferentes, llame a:

 String firstWord = "first "; String secondWord = "second"; // Create a new spannable with the two strings Spannable spannable = new SpannableString(firstWord+secondWord); // Set the custom typeface to span over a section of the spannable object spannable.setSpan( new CustomTypefaceSpan("sans-serif",CUSTOM_TYPEFACE), 0, firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannable.setSpan( new CustomTypefaceSpan("sans-serif",SECOND_CUSTOM_TYPEFACE), firstWord.length(), firstWord.length() + secondWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // Set the text of a textView with the spannable object textView.setText( spannable ); 

Esto puede funcionar: cree su propio TextView personalizado y luego utilice un StyleSpan en una parte de él:

 public class CustomTextView extends TextView { public CustomTextView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void setTypeface(Typeface tf, int style) { if (style == 1){ //replace "HelveticaBOLD.otf" with the name of your bold font tf = Typeface.createFromAsset(getContext().getApplicationContext().getAssets(), "HelveticaBOLD.otf"); }else{ //replace "HelveticaNORMAL.otf" with the name of your normal font tf = Typeface.createFromAsset(getContext().getApplicationContext().getAssets(), "HelveticaNORMAL.otf"); } super.setTypeface(tf, 0); } } 

Y entonces usted puede hacer algo como:

 int index1 = 0; //wherever bold should begin int index2 = 5; //wherever bold should end Spannable span = new SpannableString("some string"); span.setSpan(new StyleSpan(Typeface.BOLD),index1, index2,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ((CustomTextView)findViewById(R.id.yourTextView)).setText(span); 

Puede crear una vista personalizada y renderizar el texto con dos objetos Paint utilizando el método canvas.drawText

Aquí hay una solución más sencilla, puede utilizar HTML para establecer diferentes estilos en el mismo TextView .

Por ejemplo:

 // Styled label String styledText = "<big><b><font color='#333333'>title</font></b></big> <small><b><font color='#CC5490'>subtitle</font></b></small>"; // Apply the styled label on the TextView textView.setText(Html.fromHtml(styledText)); 

Necesita la siguiente importación:

 import android.text.Html; 

Yo uso este enfoque

 class FooClass { void Foo() { textViewSetText(R.id.photo_title, "Title: ", photo.getTitle()); textViewSetText(R.id.photo_tags, "Tags: ", photo.getTags()); textViewSetText(R.id.photo_author, "Author: ", photo.getAuthor()); } private void textViewSetText(int resourceId, String prefix, String text) { TextView textView = (TextView) findViewById(resourceId); SpannableString styledText = new SpannableString(prefix); styledText.setSpan(new StyleSpan(Typeface.BOLD), 0, prefix.length(), 0); textView.setText(null); textView.append(styledText); textView.append(text); } } 

Como se puede ver en " Autor ", " Título " y " Etiquetas " se ajustan a BOLD

Captura de pantalla http://image.prntscr.com/image/dd60bb4a335445c2adca8a4596d7fb32.png

¿Intentó establecer un tipo de letra personalizado en TextView antes de aplicar texto extensible?

 Typeface face = Typeface.createFromAsset(ctx.getAssets(), "fonts/boost.ttf") TextView tv = (TextView) ctx.findViewById(id); tv.setTypeface(face); 

Y luego aplicar SpannableStringBuilder a partir de la pregunta vinculada – Sólo estoy asumiendo que si su ttf soporta 'normal' y 'negrita' sería render en consecuencia 🙂

  • ¿Cómo funciona la fuente de emoji de color de Apple, y hay una versión de Android?
  • Ignorar el tamaño de fuente mínimo de la aplicación de Gmail de Android (Newsletter)
  • Cómo utilizar la fuente Roboto en TextView?
  • ¿Cómo puedo configurar mi propio tipo de letra en el renderizador AChartEngine?
  • ¿Cambiar la fuente del texto al lado del botón de radio?
  • ¿Cómo puedo apoyar el texto persa en persa en Android?
  • Multi texto de fuente en android
  • ¿Cómo cambiar la fuente de la llave del teclado de android?
  • Android: ¿Cómo encajar grandes fuentes en un pequeño botón?
  • El texto textview de Android se corta en los lados con la fuente personalizada
  • Cómo cambiar la fuente en el TextView?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.