Code example for SpannableStringBuilder

Methods: getSelectionEnd, insert, setSelection, toString

0
        final String init = "(650) 23";
        final String expected1 = "(650) 123";
        TextWatcher textWatcher = getTextWatcher();
 
        // Insert one char 
        SpannableStringBuilder number = new SpannableStringBuilder(init);
        textWatcher.beforeTextChanged(number, 4, 0, 1);
        number.insert(4, "1"); // (6501) 23
        Selection.setSelection(number, 5); // make the cursor at right of 1
        textWatcher.onTextChanged(number, 4, 0, 1);
        textWatcher.afterTextChanged(number);
        assertEquals(expected1, number.toString());
        // the cursor should still at the right of '1' 
        assertEquals(7, Selection.getSelectionEnd(number));
 
        // Insert multiple chars 
        final String expected2 = "(650) 145-6723";
        textWatcher.beforeTextChanged(number, 7, 0, 4);
        number.insert(7, "4567"); // change to (650) 1456723
        Selection.setSelection(number, 11); // the cursor is at the right of '7'.
        textWatcher.onTextChanged(number, 7, 0, 4);
        textWatcher.afterTextChanged(number);
        assertEquals(expected2, number.toString());
        // the cursor should be still at the right of '7' 
        assertEquals(12, Selection.getSelectionEnd(number));
    } 
 
    public void testStopFormatting() { 
        final String init = "(650) 123";
        final String expected1 = "(650) 123 4";