Rascalsailor
Newbie
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
:
I added the code inside the first case to create a local button1, but isn't there a better way?
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;
}