Android UI How to - Use SpannableString








The following code shows how to use SpannableString.

Example

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/my_text_view_html"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <TextView
        android:id="@+id/my_text_view_spannable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/my_text_view_html"
        android:layout_below="@+id/my_text_view_html" />

</RelativeLayout>

Java code

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;
/*from ww  w .  j a v a2s  . c om*/
public class MainActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final TextView textView1 = (TextView) findViewById(R.id.my_text_view_html);
    textView1.setText(Html.fromHtml("a string from http://java2s.com"));
    textView1.setMovementMethod(LinkMovementMethod.getInstance());

    final Spannable text2 = new SpannableString(getString(R.string.text2));
    text2.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);
    text2.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 9, 0);

    ((TextView) findViewById(R.id.my_text_view_spannable)).setText(text2);
  }
}
null