title: Dynamic mask using TextWatcher?
body: <p>I'm trying create mask using EditText with TextWatcher. This mask need format a phone number but the problem is I have two situations to this mask. Situation 1 the mask need has 13 digit <code>(99)9999-9999</code> and situation 2 need has 14 digit <code>(99)99999-9999</code>. I want when I type numbers are formatted.</p>
  
  <p>How could I do it ?</p>
  
  <p>I'm trying this.</p>
  
  <pre><code>//Activity
  private EditText etPhone;
  etPhone = (EditText)findViewById(R.id.etPhone());
  etPhone.addTextChangedListener(new TelefoneMask(etPhone));
  
  //TextWatcher
  public class TelefoneMask implements TextWatcher {
      private String current;
      private EditText phone;
      private StringBuilder mask = new StringBuilder();
  
      public TelefoneMask(EditText phone) {
          this.phone = phone;
      }
  
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  
      }
  
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
  
      }
  
      @Override
      public synchronized void afterTextChanged(Editable s) {
          // mask1 -&gt; (99)9999-9999   13 digits
          // mask2 -&gt; (99)99999-9999  14 digits
  
          Integer size = s.length();
          if(size == 10){
              mask.append(s.toString());
              mask.insert(0, "(");
              mask.insert(3, ")");
              mask.insert(8, "-");
          }else if(size &gt; 10){
              mask.setLength(0);
              mask.append(s.toString());
              mask.insert(0, "(");
              mask.insert(3, ")");
              mask.insert(9, "-");
          }
          current = mask.toString();
          phone.setText(current);
          phone.setSelection(mask.length());
      }
  }
  </code></pre>