gpt4 book ai didi

java - SwiftKey 键盘和 SpannableStringBuilder 存在结尾空格字符问题

转载 作者:行者123 更新时间:2023-12-02 11:28:00 25 4
gpt4 key购买 nike

使用 SwiftKey 键盘时,如果我将字符串从 EditText 传递到 SpannableStringBuilder 并将其设置回 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.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;
}
}

我这样做是因为我向 EditText 添加动态情感,但无法添加空格,因此我编写了一个非常简单的代码来发现问题。

最佳答案

好的,我解决了这个问题,首先必须将 inputType="textNoSuggestions"添加到 EditText;这将防止触发 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;
}
}

关于java - SwiftKey 键盘和 SpannableStringBuilder 存在结尾空格字符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49479624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com