Ok I've solved.
I intercept the contents of the clipboard before paste, manipulate it and come back to normal flow of execution. Here the code:
txtNumber.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("txtNumber","onTextChanged");
Log.d("txtNumber",s.toString());
}
@Override
public void afterTextChanged(Editable s) {
Log.d("txtNumber","afterTextChanged");
Log.d("txtNumber",s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
Log.d("txtNumber","beforeTextChanged");
Log.d("txtNumber sequence",s.toString());
Log.d("txtNumber start",Integer.toString(start));
Log.d("txtNumber count",Integer.toString(count));
Log.d("txtNumber after",Integer.toString(after));
// Gets a handle to the clipboard service.
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
String pasteData = "";
// If the clipboard doesn't contain data, disable the paste menu item.
// If it does contain data, decide if you can handle the data.
if (clipboard.hasPrimaryClip()) {
// Examines the item on the clipboard. If getText() does not return null, the clip item contains the
// text. Assumes that this application can only handle one item at a time.
ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
// Gets the clipboard as text.
pasteData = item.getText().toString();
// If the string contains data, then the paste operation is done
if (pasteData != null) {
Log.d("Paste",pasteData);
pasteData = pasteData.replace("+39", "");
pasteData = pasteData.replace(" ", "");
if (pasteData.length()!=10){
pasteData="";
}else{
String pattern= "^[0-9]*$";
if(!pasteData.matches(pattern)){
pasteData="";
}
}
ClipData clip = ClipData.newPlainText("simple text",pasteData);
clipboard.setPrimaryClip(clip);
}
}
}
});