Swap a variable from True to False and vice versa

Asked

Viewed 1,540 times

3

I created a button that when clicked creates the onClick method and makes a variable "true"

What I want is that if this button is clicked again and the variable is true it turns "false"

I’m using Android Studio, some light?

  • if I’m not mistaken, you can use arrays, and switch from true to false whenever you press

2 answers

5

A simple

variavel = !variavel;

inside your Istener solves your problem.

2


have several shakes to do this,:

public class mycActivity ... {
  boolean vaiserfalsedepois = false;
  // ...
  meubotao.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
        vaiserfalsedepois = !vaiserfalsedepois;
        // ou 
        if (vaiserfalsedepois === true)
           vaiserfalsedepois = false;
        else
           vaiserfalsedepois = true;
         // e por ai vai
     }
  });
}

hope it helps!

light and peace!

  • I understood, so inside the Oncreate method for the text of the button to change according to the variable would be: if (vaiserfalsedepois) { botaoid.setText("True"); } Else { botaoid.setText("); } ?

  • 1

    opa, dai é diferente, dai Voce pode setar uma variable texto inicada com "False" por ex, e mudar para "True" diretamente no Listener, unless you really need a boolean variable, or else try something like this: String tvar = null; tvar = vclicado.equals("verdadeiro")?"Falso":"Verdadeiro"; becomes easier and Voce avoids the if ... lse

  • 1

    ops, you have to set the value of the text of the button with the value of tvar after, ririri, was bad, for that do meubotao.setText(tvar); and voila

  • I got it, thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.