Johnny H.
Johnny H.

Reputation: 15

Detect button from previous activity

I have an activity with various buttons, and they all lead to the same activity, the second activity should change its contents depending on which button was pressed. Can I detect which button was pressed on a previous activity? How can I do that?

Thank you very much. :)

Upvotes: 1

Views: 134

Answers (1)

Reda
Reda

Reputation: 1335

Simply pass a different parameter when you click on different buttons

//First button
btn1.setOnClickListener(new OnClickListener() 
{
  @Override          
  public void onClick(View v) 
  {              
    Intent intent = new Intent();
    intent.setAction(this, SecondActivity.class);
    intent.putExtra("button", 1);
    startActivity(intent);  
  }
});

//Second button the same code but you change
intent.putExtra("button", 2);

And in the second Activity, you check the value:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  Bundle extras = getIntent().getExtras();
  if (extras != null) {
   int btnNumber = extras.getInt("button");
   switch(btnNumber) 
   {
     case 1 : ... ; break;
     case 2 : ... ; break;
   }
}

Upvotes: 2

Related Questions