Emoticons in EditText

I am trying to implement an action using EditText, which replaces some keywords with emoticons (my code at the end).

The code works fine except for one detail. If I type EditText ".sa". it is replaced with img1, but if I want to cancel it, I need to click 4 times before deleting before the image disappears (once for each char in the keyword).

This is my first time working with Spannables and donโ€™t know how to fix it. Can you help me?

public class MytestActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); EditText et = (EditText) findViewById(R.id.editText1); et.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { getSmiledText(MytestActivity.this, s); Log.e("",s.toString()); } }); } private static final HashMap<String, Integer> emoticons = new HashMap<String, Integer>(); static { emoticons.put(".sa.", R.drawable.img1); emoticons.put(".sb.", R.drawable.img2); } public static Spannable getSmiledText(Context context, Editable builder) { int index; for (index = 0; index < builder.length(); index++) { for (Entry<String, Integer> entry : emoticons.entrySet()) { int length = entry.getKey().length(); if (index + length > builder.length()) continue; if (builder.subSequence(index, index + length).toString().equals(entry.getKey())) { builder.setSpan(new ImageSpan(context, entry.getValue()), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); index += length - 1; break; } } } return builder; } } 
+6
source share
2 answers

You can try something like this:

 public void beforeTextChanged(CharSequence s, int start, int count, int after) { try { if (count == 1 && after == 0 &&// tried to delete a char s.length() >= ".sa.".length() && // string could contain an emoticon s.subSequence(start - ".sa.".length() + 1, start + 1).toString().equals(".sa.")// the last string is .sa. ) { et.setText(s.subSequence(0, s.length() - ".sa.".length())); } } catch (Exception e) { } } 

This will give a couple more problems (you will see), and this is far from a golden solution; I just wanted to give you an idea of โ€‹โ€‹how to do this. Of course, you must replace the way you use the string ".sa." ; I just coded it for simplicity.

+3
source

How about catch backspace on listener event and do it 3 times as much (or remove image space)?

+1
source

Source: https://habr.com/ru/post/903458/


All Articles