Variable that changes according to the tight button

4

I have two different methods on two different buttons. o Method onE that adds% to% of variable and Method 3 that strips% of% of variable. The problem is that when I put this variable to appear in onM the app hangs. I would have to convert this variable "int" to -1 , or am I wrong in the code structure? 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();

        }
    });
}
}
    
asked by anonymous 30.09.2016 / 04:09

1 answer

3

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

public int variavel = 0;

In order to avoid the error, simply insert "" before the variable. See below:

textoid.setText(""+variavel);

or

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

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

And finally, in order for your TextView to change at the moment you click the button, you have to setText within each button, like this:

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

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

        }
});
    
30.09.2016 / 04:20