Letter spacing in Android EditText

前端 未结 2 2148
攒了一身酷
攒了一身酷 2021-01-26 19:20

I am trying to Display a text box with letters separated by spaces.

    EditText wordText = (EditText) findViewById(R.id.word_text);
    wordText.setPaintFlags(w         


        
2条回答
  •  花落未央
    2021-01-26 19:41

    1. Make TextWatcher (this example for enter only digits into EditText field, you can change it if necessary)

      public class CustomTextWatcher implements TextWatcher{
      
          private static final char space = ' ';
      
      public CodeTextWatcher (){}
      
      @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 void afterTextChanged(Editable s) {
      
          // Remove all spacing char
          int pos = 0;
          while (true) {
              if (pos >= s.length()) break;
              if (space == s.charAt(pos) && (((pos + 1) % 2) != 0 || pos + 1 == s.length())) {
                  s.delete(pos, pos + 1);
              } else {
                  pos++;
              }
          }
      
          // Insert char where needed.
          pos = 1;
          while (true) {
              if (pos >= s.length()) break;
              final char c = s.charAt(pos);
              // Only if its a digit where there should be a space we insert a space
              if ("0123456789".indexOf(c) >= 0) {
                  s.insert(pos, "" + space);
              }
              pos += 2;
          }
      }
      

      }

    2. Attach this textWatcher to your EditText:

       EditText.addTextChangedListener(new CustomTextWatcher());
      

提交回复
热议问题