I have the strange problem when using SwiftKey Keyboard if I passed a string from EditText
to SpannableStringBuilder
and set it back to EditText
; any Space character at the end will be trimmed automatically, using default keyboard this not happen here the code:
public class MainActivity extends AppCompatActivity implements TextWatcher {
EditText txtEntry;
boolean IsChanged = false;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtEntry = (EditText) findViewById(R.id.txtEntry);
txtEntry.addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (IsChanged)
return;
IsChanged = true;
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append(txtEntry.getText());
txtEntry.setText(sb);
txtEntry.setSelection(txtEntry.getText().length());
IsChanged = false;
}
}
I m doing this as I,m adding dynamic emotions to EditText
, but can't add spaces so I made a very simple code to discover the issue.
答案 0 :(得分:0)
好的我修复了问题,首先必须在EditText中添加inputType =“textNoSuggestions”;这样可以防止两次触发OnTextChanged事件,第二次处理字符串应该抛出Editable;不要抛出EditText本身
以下是代码:
public class MainActivity extends AppCompatActivity implements TextWatcher{
EditText txtEntry;
boolean IsChanged = false;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtEntry = (EditText) findViewById(R.id.txtEntry);
txtEntry.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
txtEntry.addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String ss = "";
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (IsChanged)
return;
IsChanged = true;
String sInput =editable.toString().replace(" ","@space@");
SpannableStringBuilder ObjBuilder = new SpannableStringBuilder();
ObjBuilder.append(sInput);
while (true)
{
int iStartIndex = sInput.indexOf("@space@");
int iEndIndex = iStartIndex + "@space@".length();
if (iStartIndex == -1)
break;
sInput = sInput.replaceFirst("@space@","[space]");
Drawable ObjDraw = getResources().getDrawable(R.drawable.space);
ObjDraw.setBounds(0,0,10,60);
ImageSpan Image = new ImageSpan(ObjDraw);
ObjBuilder.setSpan(Image,iStartIndex,iEndIndex,0);
}
editable.clear();
editable.append( ObjBuilder);
txtEntry.setSelection(txtEntry.getText().length());
IsChanged = false;
}
}