Establish at least one number in EditText

1

My question is:

Is there any way to prevent the click of a button if an EditText has no number? I was able to limit minimum and maximum values (0 to 255), but I could not find a solution to this problem. Because "" is not an integer value, by clicking the button without filling in the three fields with any number, the app crashes.

I tried to use this medium, but I did not succeed:

btnCalc.setOnClickListener (new View.OnClickListener()
            {
                public void onClick(View v)
                {   
                    if (edtRed == null || edtGreen == null || edtBlue == null)
                    {
                        btnCalc.setEnabled(false);
                    }
                    else
                    {
                        btnCalc.setEnabled(true);
                        getCode();
                    }
                    if (n1 > 255 || n1 < 0 || n2 > 255 || n2 < 0 || n3 > 255 || n3 < 0)
                    {
                        result = "#FFFFFF";
                        txtResult.setText(result);
                    }
                    else
                    {           
                        Calculate();
                    }   
                    result = "#" + rst1 + remainderR + rst2 + remainderG + rst3 + remainderB;
                    txtResult.setText(result);
                }               
            });
    
asked by anonymous 09.05.2014 / 19:56

1 answer

2

Test the size of the EditText content in the listener that indicates that there has been a change in it, if the content size of your EditText is greater than zero enable the button, otherwise disable.

As the author of the question noted, the button must be initialized already disabled, because EditText starts empty. It can be disabled in both xml and code.

Example:

btnOk = (EditText)findViewById(R.id.btnOk);
btnOk.setEnabled(false); //já inicia desabilitado
txtQuantidade = (EditText)findViewById(R.id.txtQuantidade);
txtQuantidade.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        if(txtQuantidade.length() > 0 ) { //verifica tamanho do conteúdo do EditText
            btnOk.setEnabled(true);       //habilita botão
        }
        else {
            btnOk.setEnabled(false);      //desabilita botão
        }
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
}); 

Your content will always be a number, because as you said your EditText only accepts numbers:

<EditText
    android:id="@+id/txtQuantidade"
    android:inputType="number" //aceita apenas números
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:ems="10" >
</EditText>
    
09.05.2014 / 20:01