Thursday, 2 August 2012

How to create Rich text view in android


/ this is the text we'll be operating on
    SpannableString text = new SpannableString("This is red in color ");

    // make "This" (characters 0 to 4) red
    text.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, 0);

    // make "is" (characters 5 to 6) one and a half time bigger than the textbox
    text.setSpan(new RelativeSizeSpan(1.5f), 5, 6, 0);

    // make "red" (characters 7 to 9) display a toast message when touched
    final Context context = this;
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View view) {
            Toast.makeText(context, "dolor", Toast.LENGTH_LONG).show();
        }
    };
    text.setSpan(clickableSpan, 7, 9, 0);

    // make "in" (characters 10 to12) struck through
    text.setSpan(new StrikethroughSpan(), 10, 12, 0);

    // make "color" (characters13 to 18) twice as big, green and a link to this site.
    // it's important to set the color after the URLSpan or the standard
    // link color will override it.
    text.setSpan(new RelativeSizeSpan(2f), 13, 18, 0);
    text.setSpan(new URLSpan("http://www.chrisumbel.com"), 13, 18, 0);
    text.setSpan(new ForegroundColorSpan(Color.GREEN), 13, 18, 0);

    // make our ClickableSpans and URLSpans work
    richTextView.setMovementMethod(LinkMovementMethod.getInstance());

    // shove our styled text into the TextView      
    richTextView.setText(text, BufferType.SPANNABLE);

No comments:

Post a Comment