Use SpannableString

Description

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  w w w  .ja va  2 s  .co  m
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);
  }
}
Use SpannableString




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView