Reputation: 11
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.
Upvotes: 0
Views: 74
Reputation: 11
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
}
Upvotes: 0
Reputation: 1669
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 :)
Upvotes: 2
Reputation: 56
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
}
});
Upvotes: 0