Android – Spannable example

Screenshot_20160613-152414

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create spannable text and set style.
        Spannable text = new SpannableString("This is underline and bold text.");
        text.setSpan(new UnderlineSpan(), 8, 17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.setSpan(new StyleSpan(Typeface.BOLD), 22, 26, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // Set spannable text in TextView.
        TextView textView = (TextView) findViewById(R.id.textview);
        textView.setText(text);
       
        Spannable text3 = new SpannableString("Italic green text in toast");
        text3.setSpan(new StyleSpan(Typeface.ITALIC), 0, 18,  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        text3.setSpan(new ForegroundColorSpan(Color.GREEN), 0, 18,  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        Toast.makeText(this, text3, Toast.LENGTH_LONG).show();

    }
}