2012-03-08 12 views
25

Quiero aplicar dos estilos de fuente diferentes a un texto en un solo TextView.Aplicar dos estilos de fuente diferentes a un TextView

Mi caso es igual que Android - two sentences, two styles, one TextView. La única diferencia es que quiero establecer una fuente personalizada en todo el texto. He incluido Helvetica Font como un activo en mi proyecto y quiero aplicar esa fuente a TextView con la primera parte del texto Helvetica BOLD y la parte restante Helvetica NORMAL. ¿Alguna sugerencia de cómo se puede hacer?

Se necesita texto en el siguiente formato. Texto personalizado con diferentes estilos y texto único.

enter image description here

+0

, ¿por qué no se puede utilizar de dos TextView diferente con diferentes fontstyles. –

+0

@SenthilMg puede ver el motivo de esto en el enlace de referencia en la pregunta.No formateará texto como se requiere – rizzz86

+0

, supongo que debe dividir la cadena completa en dos usando regex como: y establecer en textview diferente para, por ejemplo: Texto de cadena = AAAA: BBBBB, String [] splitText = text.split (":"); tv1.setText (splitText [0]); tv2.setText (splitText [1]); –

Respuesta

69

Una forma de hacer esto 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); 
     } 
    } 

Luego, cuando desea utilizar dos tipos de letra diferentes llaman:

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); 
+0

Gracias Laurence por la respuesta. Estoy intentando este y veamos cuál será el resultado. También déjame intentar entender qué está pasando en el fragmento de código que has proporcionado) – rizzz86

+0

No hay problema, hice un pequeño cambio en el segundo bloque de código relacionado con el nombre del TypefaceSpan ampliado. En términos de implementación, CustomTypefaceSpan está listo para funcionar, solo tendrá que agregar esto a su proyecto. El segundo bloque de código es lo que necesitarás editar. – Ljdawson

+2

Laurence que funciona para mí. El problema parece ser pequeño, pero la solución es un poco compleja. Gracias por la ayuda que realmente me salvó el tiempo. – rizzz86

-2

hicieron intenta establecer una tipografía personalizada en la Vista de Texto antes de aplicar el texto spanable?

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 sus soportes ttf 'normal' y 'negrita' que harían en consecuencia :)

+0

Lo he intentado de esa manera también. Pero no aplica. – rizzz86

0

Se puede crear una vista personalizada y hacer que su texto con dos pintura objetos usando canvas.drawText método

+0

Voy a probar canvas.drawText y ver cómo funciona – rizzz86

2

Esto puede funcionar - crear su propio TextView costumbre y luego usar un StyleSpan en una parte de ella:

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); 
+0

Éste no funcionó para mí. De todos modos, gracias por la respuesta. – rizzz86

+0

Exactamente lo que estaba buscando, gracias – Ash

2

Aquí hay una solución más sencilla, puede usar 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)); 

Es necesario el siguiente importación:

import android.text.Html; 
0

utilizo 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 "Autor", "Título "y" Etiquetas "se pone en negrita

Screenshot http://image.prntscr.com/image/dd60bb4a335445c2adca8a4596d7fb32.png

Cuestiones relacionadas