character mapping in edittext android

后端 未结 4 1829
猫巷女王i
猫巷女王i 2021-02-05 22:48

I want to make my edittext like when I write character \"g\" it\'s related mapping custom character should written like here in Hindi it\'s \"जी\"

I think there should

4条回答
  •  无人及你
    2021-02-05 23:01

    To accomplish what you're after, I would create a HashMap of chars that map to other chars. If some specific char is not mapped just print it out. Here's an example I've put up:

    final HashMap charMap = new HashMap();
    charMap.put('q', '1');
    charMap.put('w', '2');
    charMap.put('e', '3');
    charMap.put('r', '4');
    charMap.put('t', '5');
    charMap.put('y', '6');
    
    final EditText editText = (EditText) findViewById(R.id.editText);
    
    editText.addTextChangedListener(new TextWatcher() {
        boolean replaced;
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.e("TAG", start + " " + before + " " + count);
            // Check in lower case
            String oldStr = s.toString().toLowerCase();
            StringBuilder newStr = new StringBuilder(s);
    
            // Loop through changed chars
            for (int i = 0; i < count; i++) {
                // Replace if a substitution is avaiable
                Character replacement = charMap.get(oldStr.charAt(start + i));
                if (replacement != null) {
                    replaced = true;
                    newStr.setCharAt(start + i, replacement);
                }
            }
    
            if (replaced) {
                replaced = false;
                editText.setText(newStr);
                // Move cursor after the new chars
                editText.setSelection(start + count);
            }
    
        }
    
        @Override
        public void afterTextChanged(Editable s) {
    
        }
    });
    

    Pros:

    • Ignores case when looking for a replacement. (q = Q = 1)
    • Replaces immediately single and multiple chars
    • Doesn't loop the whole string
    • Can replace in the middle of another string

    Cons:

    • You have to have a HashMap entry for every character you want replaced
    • ...

    As a side-note I'd like to name a few limitations that your given app's "online version" has:

    • The converting is done only when a space, new line or punctuation mark is entered.
    • You cannot add letters to already converted words.

    The apps "offline" version also has a minor bug:

    • It doesn't convert words that are copied in or written with Swipe

提交回复
热议问题