Variable that changes according to the button pressed

Asked

Viewed 303 times

4

I have two different methods on two different buttons. the Method onE adding up 3 the variable and the Method onM that takes -1 variable. The problem is that when I put this variable to appear in the textoid.setText(variavel) the app hangs. I would have to convert that "int" variable to String, or am I missing the structure of the code? Follow it:

public class MainActivity extends AppCompatActivity {

private Button botaomid;
private Button botaoeid;
private TextView textoid;
public int variavel;


public void onM () {

    variavel = variavel - 1;
}

public void onE () {

    variavel = variavel + 3;
}


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

    botaoeid =(Button) findViewById(R.id.botaoeid);
    botaomid = (Button) findViewById(R.id.botaomid);
    textoid = (TextView)findViewById(R.id.textoid);


    textoid.setText(variavel);

    botaomid.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            onM();
        }
    });


    botaoeid.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        onE();

        }
    });
}
}

1 answer

3


First you have to initialize your variable by setting a value for it. Ex.: 0.

public int variavel = 0;

To avoid error, simply insert "" before the variable. See below:

textoid.setText(""+variavel);

or

textoid.setText(String.valueOf(variavel));

Making setText(int) you are referring to a resource from the XML file, not the value itself.

And lastly, so that your TextView be changed the moment you click the button, you have to do the setText inside each button, this way:

botaomid.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            onM();
            textoid.setText(""+variavel);

        }
});
  • It worked man, thank you very much!!!!

  • @Juniorklawa No reason bro! Tamo ae!

Browser other questions tagged

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