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?
Asked
Active
Viewed 996 times
1

Muhammadjon
- 1,476
- 2
- 14
- 35
-
You can't do that with xml, but you can do that with the help of your code in Java or Kotlin – Ümañg ßürmån Nov 13 '18 at 11:12
-
Yes, I need to do it programmatically – Muhammadjon Nov 13 '18 at 11:31
-
Please check out the solution. – Ümañg ßürmån Nov 13 '18 at 17:24
-
you not understand my code – suresh madaparthi Nov 14 '18 at 03:46
2 Answers
1
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 yourString
, 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.

Ümañg ßürmån
- 9,695
- 4
- 24
- 41
-1
Yes its possible
final ClipboardManager myClipboard;
final ClipData[] myClip = new ClipData[1];
final int[] voterid;
voterid= new int[]{1, 2, 3, 4};
using Base adapter
farea.setText(voterid);
farea.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myClip[0] = ClipData.newPlainText("text", voterid);
myClipboard.setPrimaryClip(myClip[0]);
Toast.makeText(getApplicationContext(), "Text Copied",
Toast.LENGTH_SHORT).show();
}
});

suresh madaparthi
- 374
- 4
- 11