fbpx

Working with Android TextView

Everything related to TextView customization in Android SDK

Spannable TextView:

A spannable TextView can be used in Android to highlight a particular portion of text with a different color, style, size, and/or click event in a single TextView widget.

Consider that you have defined a TextView as follows:

TextView textview=findViewById(R.id.textview);

Then you can apply different highlighting to it as shown below:

Spannable color: In order to set a different color to some portion of text, a ForegroundColorSpan can be used, as shown in the following example:

Spannable spannable = new SpannableString(firstWord+lastWord); 
spannable.setSpan(new ForegroundColorSpan(firstWordColor), 0, firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(lastWordColor), firstWord.length(), firstWord.length()+lastWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
textview.setText( spannable );

Output created by the code above:

T8Bkp

Spannable font: In order to set a different font size to some portion of text, a RelativeSizeSpan can be used, as shown in the following example:

Spannable spannable = new SpannableString(firstWord+lastWord); 
spannable.setSpan(new RelativeSizeSpan(1.1f),0, firstWord.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // set size
spannable.setSpan(new RelativeSizeSpan(0.8f), firstWord.length(), firstWord.length() + lastWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // set size
textview.setText( spannable );

Output created by the code above:

cRsB6

Spannable typeface: In order to set a different font typeface to some portion of text, a custom TypefaceSpan can be used, as shown in the following example:

Spannable spannable = new SpannableString(firstWord+lastWord);
spannable.setSpan( new CustomTypefaceSpan("SFUIText-Bold.otf",fontBold), 0, firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan( new CustomTypefaceSpan("SFUIText-Regular.otf",fontRegular), firstWord.length(), firstWord.length() + lastWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setText( spannable );

However, in order to make the above code working, the class CustomTypefaceSpan has to be derived from the class TypefaceSpan. This can be done as follows:

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);
    }
}

Strikethrough TextView

Strikethrough the entire text

String sampleText = "This is a test strike";
textView.setPaintFlags(tv.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
textView.setText(sampleText);

Output: This is a test strike

Strikethrough only parts of the text

String sampleText = "This is a test strike";
SpannableStringBuilder spanBuilder = new SpannableStringBuilder(sampleText); 
StrikethroughSpan strikethroughSpan = new StrikethroughSpan(); spanBuilder.setSpan(
strikethroughSpan, // Span to add 
0, // Start
4, // End of the span (exclusive)
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE // Text changes will not reflect in the strike changing
);
textView.setText(spanBuilder);

Output: This is a test strike

TextView with image

Android allows programmers to place images at all four corners of a TextView. For example, if you are creating a field with a TextView and at same time you want to show that the field is editable, then developers will usually place an edit icon near that field. Android provides us an interesting option called compound drawable for a TextView:

<TextView
android:id="@+id/title"
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_centerInParent="true" 
android:drawablePadding="4dp" 
android:drawableRight="@drawable/edit" 
android:text="Hello world" 
android:textSize="18dp" />

You can set the drawable to any side of your TextView as follows:

android:drawableLeft="@drawable/edit"
android:drawableRight="@drawable/edit"
android:drawableTop="@drawable/edit"
android:drawableBottom="@drawable/edit"

Setting the drawable can also be achieved programmatically in the following way:

yourTextView.setCompoundDrawables(leftDrawable, rightDrawable, topDrawable, bottomDrawable);

Setting any of the parameters handed over to setCompoundDrawables() to null will remove the icon from the corresponding side of the TextView.

Make RelativeSizeSpan align to top

In order to make a RelativeSizeSpan align to the top, a custom class can be derived from the class SuperscriptSpan. In the following example, the derived class is named TopAlignSuperscriptSpan:

activity_main.xml:

<TextView
   android:id="@+id/txtView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginTop="50dp"
   android:textSize="26sp" />

MainActivity.java:

TextView txtView = (TextView) findViewById(R.id.txtView);
SpannableString spannableString = new SpannableString("RM123.456"); 
spannableString.setSpan( new TopAlignSuperscriptSpan( (float)0.35 ), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
txtView.setText(spannableString);

TopAlignSuperscriptSpan.java:

private class TopAlignSuperscriptSpan extends SuperscriptSpan { 
  //divide superscript by this number
  protected int fontScale = 2;
  //shift value, 0 to 1.0
  protected float shiftPercentage = 0; //doesn't shift
  TopAlignSuperscriptSpan() {}
  //sets the shift percentage
  TopAlignSuperscriptSpan( float shiftPercentage ) {
    if( shiftPercentage > 0.0 && shiftPercentage < 1.0 )
      this.shiftPercentage = shiftPercentage;
  }
  @Override
  public void updateDrawState( TextPaint tp ) {
    //original ascent
    float ascent = tp.ascent(); //scale down the font
    tp.setTextSize( tp.getTextSize() / fontScale ); //get the new font ascent
    float newAscent = tp.getFontMetrics().ascent;
    //move baseline to top of old font, then move down size of new font 
    //adjust for errors with shift percentage
    tp.baselineShift += ( ascent - ascent * shiftPercentage ) - (newAscent - newAscent * shiftPercentage );
  }
  @Override
  public void updateMeasureState( TextPaint tp ) {
    updateDrawState( tp );
  }
}

Reference screenshot:

USMOj

Here Have Some Customization of TextView In Android.

Android

If you are interested to Learn then

Register for

Training Classes