Ahmed Laoun Ahmed Laoun - 5 months ago 10
Android Question

Can I use one definition of two Button by switching between them?

I have this two ImageButton views redButton and blueButton
but in the code i used just one definition

ImageButton GButton = (ImageButton) findViewById(R.id.blueButton);


Then in the
clickListener
I have this code:

GButton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case (R.id.blueButton):
GButton = (ImageButton) findViewById(R.id.redButton);
break;

case (R.id.redButton):
GButton = (ImageButton) findViewById(R.id.blueButton);
break;
}
}
});


I want the
clickListener
to switch to the
redButton
. But it doesn't.

Answer

Answer :

Yes you can use one definition of two Button by switching between them.

Problem :

Your code is not working because you haven't set clickListner after switching id's of GButton.

Do it like this and it will start working :

GButton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
    switch (v.getId()) {
        case (R.id.blueButton):
            Toast.makeText(MainActivity.this, "blue", Toast.LENGTH_SHORT).show();
            GButton = (ImageButton) findViewById(R.id.redButton);

            //ADD IT HERE

            GButton.setOnClickListener(this);
        break;

        case (R.id.redButton):
            Toast.makeText(MainActivity.this, "red", Toast.LENGTH_SHORT).show();
            GButton = (ImageButton) findViewById(R.id.blueButton);

            //ADD IT HERE

            GButton.setOnClickListener(this);
        break;
    } 
}
});