Search code examples
androidandroid-edittexttextwatcher

How can I put a question mark at the end of the edittext as in quora?


How can I add question mark(?) at the end of the EditText as user type into it. On every textchanged question mark should remain at the end of the edittext just like it is happen in Quora. I am using the textwatcher to change the text and place the question mark at the end but I am not getting the exact logic.

textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            questionTxt.removeTextChangedListener(textWatcher);
            questionTxt.setText(questionTxt.getText().toString().replace("?", ""));
            questionTxt.setSelection(questionTxt.getText().length()-1);
            questionTxt.setText(questionTxt.getText().toString()+"?");
            questionTxt.addTextChangedListener(textWatcher);
            questionTxt.addTextChangedListener(textWatcher);

        }

        @Override
        public void afterTextChanged(Editable editable) {
            questionTxt.setSelection(editable.length());
            if (questionTxt.getText().toString().length() <= 0)
                questionTxt.setError("Enter question");
        }
    };

    questionTxt.addTextChangedListener(textWatcher);

Please refer below Image for reference.

enter image description here


Solution

  • The best way to obtain that is to create TextWatcher just like this:

    textWatcher = new TextWatcher() {
        @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 (editable.length() == 0) {
                return;
            }
    
            String text = editable.toString();
            int indexOfQuestionMark = text.lastIndexOf("?");
            if (indexOfQuestionMark == -1 || indexOfQuestionMark != text.length() - 1) {
                editable.append("?");
            }
        }
    };
    
    questionTxt.setHint("Enter question")
    questionTxt.addTextChangedListener(textWatcher);
    

    With little tuning your solution should work perfectly :)

    I've set a hint instead of setting error in question txt. This way user will see text "Enter question" when nothing is entered.

    "Alghoritm" is searching for '?' occurence in non empty input. If it is at the end -> then nothing to do. If it is not found, or is found somewhere inside text -> then question mark is added in the end.

    Notice that this TextWatcher implementation is not dependent on questionTxt so you can put it in another file.