• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

making a variable visible in switch statement

Hi all - In the code below, I need the variables button1 and button2 to be visible in the switch statement to change their button text after being clicked.The switch statement happliy uses their button id's to decide which was clicked, but it can't see the button1 or button2 variables in the switch statement when I try to do a simple statement like
Java:
button1.setText("Clicked2");
:
I added the code inside the first case to create a local button1, but isn't there a better way?
Java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

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

        Button button1 = (Button)findViewById(R.id.button1);
        Button button2 = (Button)findViewById(R.id.button2);

        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
    }
            @Override
            public void onClick(View v) {
                switch(v.getId()){
                    case R.id.button1:
                        Button button1 = (Button)findViewById(R.id.button1);
                        button1.setText("Click Me !");
                        Toast.makeText(MainActivity.this, "Button1", Toast.LENGTH_SHORT).show();
                    break;
                    case R.id.button2:
                        //button2.setText("Clicked2"); // can't see the variable button2
                        Toast.makeText(MainActivity.this, "Button2", Toast.LENGTH_SHORT).show();
                        break;

                }
 
Ah - I think I've answered my own question - add global variable declarations. I originally did this but, didn't remove the second declaration further down to button1 and button2:
So I have
Java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
   private  Button button1;
    private Button button2;
 
Back
Top Bottom