我有一个EditText实现TextWatcher但Backspace键有问题.
保持退格时,前5个字符逐个清晰,但保留退格时,转换为图像的最后5个字符不能逐个清除.
看图像:
> 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;}}
> 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 – 保持退格不会逐个清除文本全部内容,希望文章能够帮你解决android – 保持退格不会逐个清除文本所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)