我迟到了,但在我的旧平板电脑上,我的 EditText 也可以像你说的那样工作。
所以,我像下面这样修复它。
1.创建一个类来存储起始索引和插入字符串的长度信息。
public class PasteUnit {
int start = 0;
int length = 0;
public PasteUnit(int start, int length) {
this.start = start;
this.length = length;
}
}
2.创建一个扩展EditText的类。
public class MyEditText extends EditText
{
boolean pasteStarted = false;
ArrayList<PasteUnit> pasteUnits = new ArrayList<>();
public MyEditText(Context context)
{
super(context);
}
public MyEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public MyEditText(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
public boolean onTextContextMenuItem(int id) {
if(id==android.R.id.paste) {//This is called when the paste is triggered
pasteStarted = true;
}
boolean consumed = super.onTextContextMenuItem(id);
//the super.onTextContextMenuItem(id) processes the pasted string.
//This is where EditText acts weird.
//And we can watch what is happening in our TextWatcher to be added below
switch (id){
case android.R.id.paste://This is called after we collected all the information
if(pasteUnits.size()>1) {//When a space or spaces are inserted
int startIndex = pasteUnits.get(0).start;
int totalLength = 0;
for(int i=0;i<pasteUnits.size();i++) {
PasteUnit pasteUnit = pasteUnits.get(i);
totalLength = totalLength + pasteUnit.length;
}
int endIndex = startIndex + totalLength;
String string = this.getText().toString();
String before = string.substring(0, startIndex);
String after = string.substring(endIndex);
PasteUnit lastPasteUnit = pasteUnits.get(pasteUnits.size()-1);
String lastString = string.substring(lastPasteUnit.start, lastPasteUnit.start + lastPasteUnit.length);
String result = before + lastString + after;
this.setText(result);
this.setSelection(startIndex + lastString.length());
}
pasteUnits.clear();
pasteStarted = false;
break;
case android.R.id.copy:
break;
case android.R.id.cut:
break;
}
return consumed;
}
}
3.将 TextWatcher 添加到您的 EditText。
看到 TextWatcher,旧的 EditText 的行为真的很奇怪。当您将字符串 A 粘贴到字符串 B 中时,它首先在字符串 B 中插入一个空格,然后在字符串 B 中插入另一个空格,最后在两个空格之间插入字符串 A。
在其他情况下,例如在字符串 B 之后粘贴字符串 A,它首先在字符串 B 之后附加一个空格,然后再附加字符串 A。
所以无论如何它似乎在最后一步插入原始字符串。
MyEditText edit = (MyEditText) findViewById(R.id.mainEditText1);
edit.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(edit.pasteStarted) {//when it is processing what we pasted
edit.pasteUnits.add(new PasteUnit(start, count));
//store the information about the inserted spaces and the original pasted string
}
}
});