Pedro Costa
Pedro Costa

Reputation: 21

How to fill on the run a textView while typing something in a plainText

so I have an empty plain text and beside that I have an empty textview.

EditText editText = (EditText) findViewById(R.id.TextVw);
TextView textView = (TextView) findViewById(R.id.textView);
String example = editText.getText().toString();

So, when I start to type something inside the Edittext(edittext), It should appear at the same time(live) into the TextView(textview) The (example) is the text you get from the editText. How can I do that?

Upvotes: 0

Views: 73

Answers (1)

Rishabh Kamdar
Rishabh Kamdar

Reputation: 166

Well a short and simple answer would be to update the textView on editText's text change. Implement the on text change listener for editText like this:

editText.addTextChangedListener(object: TextWatcher{
        override fun afterTextChanged(p0: Editable?) {
            //This is where you set the text in the text view
            //Also check if string is not empty or null, if its null, then set "" as textView's text
            p0?.let{
                if(it.toString().isNotEmpty()){
                    textView.setText(it.toString())        
                }else{
                    textView.setText("")
                }
            } ?: run {
                textView.setText("")
            }
            
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            //This will return the previous value of editText before user typed a character
            Log.d("Example", "beforeTextChanged: ${p0.toString()}")
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            //This gives the live value of what the user just typed.
            Log.d("Example", "onTextChanged: ${p0.toString()}")
        }

    })

Sorry I am using kotlin so this answer is also for kotlin. But the implementation is same for java.

Please let me know if any issues!

Upvotes: 1

Related Questions