0

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.

Natig Babayev
  • 3,128
  • 15
  • 23

3 Answers3

2

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 :)

Brian H.
  • 1,603
  • 11
  • 16
  • Hello @Ryann, Thank you very much for your help. And I'm sorry for the delayed feedback. Since I'm a beginner on both Android and Kotlin, it took me a little while to implement your suggestion. Turns out that Kotlin offers simplified access to the override functions. I have posted the final implementation below, for everybody's information. Thank you again for your support! – Rodrigo Tomaz Jun 18 '20 at 18:46
0

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
       }
      });
0

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
    }