How to disable Button if EditText is empty ?
Here's a super simple answer in Kotlin.
Just replace 'EditText' and 'Button' with your own.
Button.isEnabled = false
EditText.addTextChangedListener(object: TextWatcher {
override fun onTextChanged(s:CharSequence, start:Int, before:Int, count:Int) {
Button.isEnabled = s.toString().trim{ it <= ' ' }.isNotEmpty()
}
override fun beforeTextChanged(s:CharSequence, start:Int, count:Int,
after:Int) {
}
override fun afterTextChanged(s: Editable) {
}
})
For Multiple EditTexts go
Button.isEnabled = false
val editTexts = listOf(editText1, editText2, editText3, editText4, editText5, editText6)
for (editText in editTexts) {
editText.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
var et1 = editText1.text.toString().trim()
var et2 = editText2.text.toString().trim()
var et3 = editText3.text.toString().trim()
var et4 = editText4.text.toString().trim()
var et5 = editText5.text.toString().trim()
var et6 = editText6.text.toString().trim()
computeBtn.isEnabled = et1.isNotEmpty()
&& et2.isNotEmpty()
&& et3.isNotEmpty()
&& et4.isNotEmpty()
&& et5.isNotEmpty()
&& et6.isNotEmpty()
}
override fun beforeTextChanged(
s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun afterTextChanged(
s: Editable) {
}
})
}
Simple just check the condition in onCreate
if (et.getText().toString().trim().equals("")){
button.setEnabled(false);
}
else{
button.setEnabled(true);
}
Use TextChangedListener
and initially disable ImageButton
in onCreate().
Try this
public class MyActivity extends Activity {
ImageButton imb;
EditText et;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imb = (ImageButton) findViewById(R.id.btn_send);
et = (EditText) findViewById(R.id.EditText1);
imb.setEnabled(false); // set button disable initially
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
if (s.toString().equals("")) {
imb.setEnabled(false);
} else {
imb.setEnabled(true);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
}
editText1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length()==0){
button.setEnabled(false);
} else {
button.setEnabled(true);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});