ghostrider
ghostrider

Reputation: 5259

Buttons and OnClick Listener

I am having 3 buttons on my layout. I want when each of it is pressed to go to a different screen. What I should do is something like this or something more complicated?

b1=(Button)findViewById(R.id.Button01);
b1.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
      FirstButtonClicked();
}
});

b2=(Button)findViewById(R.id.Button02);
b2.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    SecondButtonClicked();}
});

b3=(Button)findViewById(R.id.Button03);
b3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ThirdButtonClicked();}
});

Must i return anything regarding the button pressed or if the first button is pressed (for example) the second and the third will not run at all? Alos, They must be defined inside my onCreate or could I define them outside,as a new function called CheckButtons(); and just call it from my on.Create() (or whenever else i want to check those buttons)?

Upvotes: 1

Views: 455

Answers (3)

Vivekanand
Vivekanand

Reputation: 755

you could try this... This is the easy way out though...

public class StackOverFlow extends Activity implements OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Button b1,b2,b3;
    Intent i;

    b1= //get handle
    b2= //get handle
    b3= //get handle
}

public void onClick(View v) {

    switch (v.getId()) {
    case b1:
        i=new Intent(StackOverFlow.this,destination1.class);
        break;

    case b2:
        i=new Intent(StackOverFlow.this,destination2.class);
        break;

    case b3:
        i=new Intent(StackOverFlow.this,destination3.class);
        break;
    default:
        break;
    }
}

}

Upvotes: 1

xagema
xagema

Reputation: 773

This code is correct. To go to the other screen, you do:

Intent i = new Intent(this, OtherScreen.class);
startActivity(i);

and AndroidManifest.xml put permission for OtherScreen on tag Application:

 <activity android:name=".OtherScreen"> </activity>

Upvotes: 3

Matt Harris
Matt Harris

Reputation: 3544

Like you have it there is just fine. In the buttonclicked methods 1,2,3 you just need to start an intent to run the activity you want.

You need to change the id of each button though, R.id.Button01, R.id.Button02, R.id.Button03

Upvotes: 2

Related Questions