gpt4 book ai didi

android - 按住退格键不会一一清除文本

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:33 24 4
gpt4 key购买 nike

我有一个 EditText 实现 TextWatcher,但退格键有问题。按住退格键时前5个字符会被一一清除,但转换为图像的后5个字符在按住退格键时无法一一清除。

看图:

enter image description here

  1. MainActivity.java

    public class MainActivity extends AppCompatActivity {
    Spannable.Factory spannableFactory;

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    spannableFactory = Spannable.Factory
    .getInstance();

    final EditText editText = (EditText) findViewById(R.id.editText);
    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) {
    editText.removeTextChangedListener(this);
    if (s.length() >= 5) {
    editText.setText(getTextToIcon(getApplicationContext(), s));
    }
    if(count!=0){ // != key delete
    if (s.length() - 1 > start) {
    editText.setSelection(start + 1);
    } else {
    editText.setSelection(s.length());
    }
    }else{ // = key delete
    editText.setSelection(start);
    }

    editText.addTextChangedListener(this);
    }

    @Override
    public void afterTextChanged(Editable s) {}
    });
    }


    public Spannable getTextToIcon(Context context, CharSequence text) {
    StringBuilder stringBuilder = new StringBuilder(text);
    Spannable spannable = spannableFactory.newSpannable(stringBuilder);
    int index = text.length() - 1;
    for(int i = 5; i<=index; i++){
    spannable.setSpan(new ImageSpan(context, android.R.drawable.star_on),
    i, i + 1,
    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return spannable;
    }
    }
  2. activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLength="10"
    android:inputType="number" />
    </LinearLayout>

最佳答案

兄弟,有bug的代码如下:

if (s.length() >= 5) {
editText.setText(getTextToIcon(getApplicationContext(), s));
}

你应该把它改成这样:

if (count != 0 && s.length() >= 5) {
// just set the text to the icon in input state instead of pressing delete key in soft method
editText.setText(getTextToIcon(getApplicationContext(), s));
}

希望对您有所帮助。

关于android - 按住退格键不会一一清除文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37801966/

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