NikanDalvand NikanDalvand - 3 months ago 6
Android Question

Android - Running next if on second button click

as subject says I'm looking for a way to run first if on first click on the button and run next if on click on the button
Here is what i tried

final Button button = (Button) findViewById(R.id.welcomeButton);
final TextView textView = (TextView) findViewById(R.id.welcomeText);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View p1)
{

int x = 1;

if (x == 1)
{
textView.setText(R.string.step1);
button.setText("Next");

// heres increment of the variable x so on next click x will be 2 and the next if will be run instead
x++;
}
if (x == 2)
{
textView.setText(R.string.step2);
button.setText("Next");
}


}
});


as you can see there's a increment on first
if
so it increases the variable x and next time that button is clicked x is 2 and second one will run ,
but the problem is on first button click it runs the first
if
then increase the variable and runs next
if
i want it to run first if only on first click . how can i do this in this method ?
is it better to use a
case
if yes please give me an example of it
thanks in advance

Answer

You need to make x a member variable of your class. So somewhere in your class you have to define it like

private int x = 1;

and change your onClick method to this

@Override
public void onClick(View p1)
{
    if (x == 1)
    {
        textView.setText(R.string.step1);
        button.setText("Next");

        // heres increment of the variable x so on next click x will be 2 and the next if will be run instead
        x++;
    }
    if (x == 2)
    {
        textView.setText(R.string.step2);
        button.setText("Next");
    }
}

You probably need to reset x somewhere too

Comments