Monday, June 25, 2012

Android SpannableStringBuilder Example



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

<EditText 
        android:id="@+id/editText1"
        android:layout_marginTop="10dp"
        android:layout_width="fill_parent"
        android:textSize="50.0dp"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
<TextView 
        android:id="@+id/txtview"
        android:layout_width="fill_parent"
        android:textSize="25.0dp"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:text="SpannableStringBuilder" />
</LinearLayout>




SpannableStringBuilderActivity.java:
public class SpannableStringBuilderActivity extends Activity {
 private EditText et;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  et = (EditText) this.findViewById(R.id.editText1);
  et.setText("HelloWorld");
  this.setstyle(3, 7);
    }
 public void setstyle(int start, int end) {
  SpannableStringBuilder spannable = new SpannableStringBuilder(getText()
    .toString());
  CharacterStyle span1 = new UnderlineSpan();
  spannable.setSpan(span1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  ForegroundColorSpan span2 = new ForegroundColorSpan(Color.RED);
  spannable.setSpan(span2, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
   CharacterStyle span3=new StyleSpan(android.graphics.Typeface.ITALIC); 
   spannable.setSpan(span3, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  setText(spannable);
 }
 private Editable getText() {
  return et.getText();
 }

 private void setText(SpannableStringBuilder spannalbe) {
  et.setText(spannalbe);

 }
}


Download Source Code: SpannableStringBuilder









0 comments:

Post a Comment

 
Powered by Blogger