Search code examples
androidandroid-edittextclipboardmanager

Pasting only numbers from the Clipboard


InputType of EditText in my application is number, only. How can I paste only numbers from clipboard to this EditText, if text in clipboard contains both numbers and letter?


Solution

  • Solution: There are 2 things which came up.

    Firstly: As I've tested your question, if you have set EditText as android:inputType="number" then it behaves exactly how you want. If you paste an alphanumeric string then it shows only number. It doesn't show Alphabets or any special characters at all. This was tested in my device Android 7.1.1 (API25).

    Secondly: If You still want to use a workaround which suits your need then you can use TextWatcher:

    • Step1: Make an EditText global object in which you will paste your String, and initialize it:

      EditText editText;
      

      then in your onCreate():

      editText = findViewById(R.id.your_editText);
      
    • Step2: Add the TextWatcher

      editText.addTextChangedListener(new TextWatcher() {
          @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) {
              ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
              try {
                  CharSequence txt = clipboard.getPrimaryClip().getItemAt(0).getText();
                  String str = getOnlyNumbers(txt.toString());
                  editText.setText(str);
              } catch (Exception e) {
                  return;
              }
          }
      });
      
    • Step3: Add the below method in your class to rescue only numbers:

      public String getOnlyNumbers(String str) {
      
          str = str.replaceAll("[^\\d.]", "");
      
          return str;
      
      }
      

    I hope this will help. If you have any doubts, please comment below.