I am trying to do something but I don't know how to do it. Let's see if someone can help me.
I have a EditText
and my intention is that depending on what you write in it, clicking on my Boton
will execute one method and another.
For example, that the correct words are only: " Hello ", " Salut " and Hello ", if you write one of those three words and click on btn1
it, the first method is executed. But if you write any other word or none, it is executed the second method.Is this possible?
I leave here what I have been able to do with the code.
public class Main5Activity extends AppCompatActivity {
EditText text1;
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
text1 = (EditText) findViewById(R.id.text1);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// si la palabra es correcta:
Toast.makeText(Main5Activity.this, "Correcto!", Toast.LENGTH_LONG).show();
// si la palabra no es correcta o no se ha escrito nada:
Toast.makeText(Main5Activity.this, "No es correcto", Toast.LENGTH_LONG).show();
}
});
}
}
Declare an array with the words, this so you don't have to write an extensive code if you need more words and write many comparisons in one line (avoid cyclomatic complexity ), it is also more optimal:
performs a comparison with the text inside the
EditText
:and even if you use an Array you can use :
You can try using an Array with the response words (options), and then use Arrays.asList(yourArray).contains(yourValue) to see if the word you typed in the EditText is within the correct options.
It would be something like this:
So simple:
What you ask for can be done simply in a check within the button's click Listener. It would suffice to verify that the entered word is one of those three that you have put ( "Hello", "Salut" and Hello" ) using a
if-else
PS: In the example I have put the check to be done regardless of the case with the function
equalsIgnoreCase("hola")
(if you want the words to be exactly the ones you put instead of using the function weequalsIgnoreCase("hola")
would use the functionequals("Hola")
)I hope it helps you!