put # before the word written edit text Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of put # before the word written edit text without wasting too much if your time.

The question is published on by Tutorial Guruji team.

how to put # character before the word in edittext?

what I want : I wanna put # character before the every word written in edit text

every word starts with #

for example :

#hello #world #hi


Answer

Try this TextWatcher.

class SharpWordsTextWatcher: TextWatcher {

    private var addSharp: Boolean = false
    private var isEmpty = false

    override fun afterTextChanged(s: Editable) {
        if(addSharp) {
            s.insert(s.length - 1, "#")
        }
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
        isEmpty = s.isEmpty() || s.last() == ' '
    }

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        addSharp = isEmpty && s.last() != ' ' && count != 0
    }

}

And add this to your EditText.

myEditText.addTextChangedListener(SharpWordsTextWatcher())
We are here to answer your question about put # before the word written edit text - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji