Code example for SpannableStringBuilder

Methods: delete, getSelectionEnd, insert, length, setSelection, toString

0
        final String init = "(650) 123";
        final String expected1 = "(650) 123 4";
        TextWatcher textWatcher = getTextWatcher();
 
        // Append space 
        SpannableStringBuilder number = new SpannableStringBuilder(init);
        textWatcher.beforeTextChanged(number, 9, 0, 2);
        number.insert(9, " 4"); // (650) 123 4
        Selection.setSelection(number, number.length()); // make the cursor at right of 4
        textWatcher.onTextChanged(number, 9, 0, 2);
        textWatcher.afterTextChanged(number);
        assertEquals(expected1, number.toString());
        // the cursor should still at the right of '4' 
        assertEquals(expected1.length(), Selection.getSelectionEnd(number));
 
        // Clear the current string, and start formatting again. 
        int len = number.length();
        textWatcher.beforeTextChanged(number, 0, len, 0);
        number.delete(0, len);
        textWatcher.onTextChanged(number, 0, len, 0);
        textWatcher.afterTextChanged(number);
 
        final String expected2 = "(650) 123-4";
        number = new SpannableStringBuilder(init);