Code example for SpannableStringBuilder

Methods: append, getSelectionEnd, length, setSelection, toString

0
public class PhoneNumberWatcherTest extends AndroidTestCase {
    public void testAppendChars() { 
        final String multiChars = "65012345";
        final String formatted1 = "(650) 123-45";
        TextWatcher textWatcher = getTextWatcher();
        SpannableStringBuilder number = new SpannableStringBuilder();
        // Append more than one chars 
        textWatcher.beforeTextChanged(number, 0, 0, multiChars.length());
        number.append(multiChars);
        Selection.setSelection(number, number.length());
        textWatcher.onTextChanged(number, 0, 0, number.length());
        textWatcher.afterTextChanged(number);
        assertEquals(formatted1, number.toString());
        assertEquals(formatted1.length(), Selection.getSelectionEnd(number));
        // Append one chars 
        final char appendChar = '6';
        final String formatted2 = "(650) 123-456";
        int len = number.length();
        textWatcher.beforeTextChanged(number, number.length(), 0, 1);
        number.append(appendChar);
        Selection.setSelection(number, number.length());
        textWatcher.onTextChanged(number, len, 0, 1);
        textWatcher.afterTextChanged(number);
        assertEquals(formatted2, number.toString());
        assertEquals(formatted2.length(), Selection.getSelectionEnd(number));
    } 
 
    public void testRemoveLastChars() { 
        final String init = "65012345678";
        final String result1 = "(650) 123-4567";