0

I have 2 buttons and 1 number field, if I press a button without something in the field, it crashes, so what I want to do is disable the buttons unless the number field has something in it, I have looked around for an answer but either they aren't relevant, or I'm not sure how it would fit into my code, here are the two onClick functions for each button. Thanks

public void toPounds(View view){
    EditText amount = (EditText)findViewById(R.id.amount);

    Double omrAmount = Double.parseDouble(amount.getText().toString());

    Double gbrAmount = omrAmount * 1.79;

    Toast.makeText(getApplicationContext(), "£" + gbrAmount.toString(), Toast.LENGTH_LONG).show();
}

public void toRiyals(View view){
    EditText amount = (EditText)findViewById(R.id.amount);

    Double gbrAmount = Double.parseDouble(amount.getText().toString());

    Double omrAmount = gbrAmount / 1.79;

    Toast.makeText(getApplicationContext(), omrAmount.toString() + " Riyals", Toast.LENGTH_LONG).show();
}

3 Answers3

0
    yourField.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) {
          if(s.length() == 0)
            button1.setEnabled(false)
         else
         button1.setEnabled(true)
       }
      });

link

Community
  • 1
  • 1
caliskan
  • 107
  • 1
  • 6
0

If you want to disable buttons if edit text is empty then you can do the following :

EditText amount = (EditText)findViewById(R.id.amount);
Button button = (Button) findViewById(R.id.button1);
if(amount.getText().toString().isEmpty()){
   button.setEnabled(false);
}

amount.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) {
      if(s.length() == 0)
        button1.setEnabled(false)
     else
     button1.setEnabled(true)
   }
  });
0

Not specifically an answer to your question, but generally speaking you would want to add some sort of check before you call your code which now crashes your application. It's not a good idea to to have code which crashes your app lingering around.

Maybe make a method like: isMyEditTextValid(...){..}

Linxy
  • 2,525
  • 3
  • 22
  • 37