Android TextView: how can I change layout dynamically as text is typed

74 views Asked by At

I need to set a button to "visible" or "gone" dynamically as user types on a TextView field. By using the statement below, I have been able to accomplish it when Enter is pressed, but that would be great if the button becomes visible or gone immediately as the user types or deletes the text content. Any suggestion?

binding.textField.setOnEditorActionListener { v, actionId, event -> 
    if (v.text.toString().trim().isEmpty()){
        binding.button.visibility = View.GONE
    } else{
        binding.button.visibility = View.VISIBLE
    }

    return@setOnEditorActionListener true
}

Thank you in advance for your attention! Rodrigo Tomaz.

3

There are 3 answers

1
Poorya Taghizade On

you should add textchangelistner to your editext and hide button on text change

binding.textField.addTextChangedListener(new TextWatcher() {

       @Override
       public void afterTextChanged(Editable s) {}

       @Override    
       public void beforeTextChanged(CharSequence s, int start,
         int count, int after) {
       }

       @Override    
       public void onTextChanged(CharSequence s, int start,
         int before, int count) {
        binding.button.visibility = View.GONE
       }
      });
1
Brian H. On

You can use addTextChangedListener on your EditText.

Like this:

binding.textField.addTextChangedListener(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.toString().trim().isEmpty()){
               binding.button.visibility = View.GONE
            } else{
               binding.button.visibility = View.VISIBLE
            }

        }
    });

Hope that help :)

0
Rodrigo Tomaz On

Kotlin offers a simplified access to the override functions. Here's my final (working) implementation, fyi:

binding.textField.doAfterTextChanged { text: Editable? ->
    if (text.toString().trim().isEmpty()){
        binding.button.visibility = View.GONE
    } else{
        binding.button.visibility = View.VISIBLE
    }