Search code examples
xamarin.androidtextviewandroid-spannable

The effect of BufferType.Normal and BufferType.Spannable for textView


I have this code:

    TextView tv1 = FindViewById<TextView>(Resource.Id.textView1);
    tv1.Text = "Text";
    SpannableString wordtoSpan = new SpannableString(tv1.Text);
    wordtoSpan.SetSpan(new UnderlineSpan(), 0, tv1.Text.Length, 0);
    tv1.SetText(wordtoSpan, TextView.BufferType.Normal);

Whether I use BufferType.Normal or BufferType.Spannable, A line is drawn below the text, a line appears below the text. So what is the effect of BufferType.Normal and BufferType.Spannable?


Solution

  • TextView.BufferType:

    • Normal: normal;
    • Editable: characters can be appended;
    • Spannable: use styles in the given character area;

    The type of the text buffer that defines the characteristics of the text such as static, styleable, or editable. It could be used for changing the TextView in runtime.

    TextView.BufferType.Editable: Insert

          TextView tv2 = FindViewById<TextView>(Resource.Id.textView2);
            tv2.SetText("Hello", TextView.BufferType.Editable);
            var s = tv2.EditableText;
            s.Insert(1, " Hello");
    

    OutPut:

    enter image description here

    TextView.BufferType.Spannable: set the different color in a single Textview

    TextView tv3 = FindViewById<TextView>(Resource.Id.textView3);
            tv3.Text = "Hello World";
            SpannableString wordtoSpan3 = new SpannableString(tv3.Text);
            wordtoSpan3.SetSpan(new ForegroundColorSpan(Color.Red), 0, 5, 0);  // "Hello" is red
            wordtoSpan3.SetSpan(new ForegroundColorSpan(Color.Blue), 7, 11, 0); // "orld" is blue
            tv3.SetText(wordtoSpan3, TextView.BufferType.Spannable);
    

    Output:

    enter image description here