Domanda

I use .setError function. But it checks the text field only when the save button is clicked, go to SecondActivity and press Back button on device to see it can't be left empty!

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_card);

save=(Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {

@Override   
public void onClick(View v) {

EditText Name2 = (EditText)findViewById(R.id.txtName);
if( Name2.getText().toString().length() == 0 )
Name2.setError( "First name is required!" );

Intent intent = new Intent(NewCard.this, Template.class);
startActivity(intent);

}
});

Any idea on how i can check when button is clicked but not proceeding to SecondActivity if Name2 is blank? And beside length(), i also want to check for numbers, undesired characters etc. if possible. Thanks for assistance.

È stato utile?

Soluzione

You just need to create an else for your if, then move your call to startActivity() into that like so:

// Expand this condiditional to perform whatever other validation you want
if( Name2.getText().toString().length() == 0 ) {
    Name2.setError( "First name is required!" );
} else {
    // Validation passed, show next Activity
    Intent intent = new Intent(NewCard.this, Template.class);
    startActivity(intent);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top