Reputation: 75
I was wondering if there is any way to call the same activity for different buttons, but do different things for each one..
More specific.. I have one activity with about 10 buttons on it and if I do it traditionally, every time I press a button, I have to create an activity for each one and as a result, I will have more than 15 java files..
So, I was wondering if there is any way, all the buttons, show to the same activity (which is easy, I will "intent" to show the same activity), but on that activity, depending on the button I press, do different actions..
For example, all the buttons show on Buttons.java, but inside exist a TextView and every time show another text, depending on the buttons I press -> Text1 (for Button1), Text2 (for Button2), Text3 (for Button3)...
Do you have any ideas?? Thank you!!
Upvotes: 0
Views: 2210
Reputation: 2179
You can pass some information to activity when you want to start it... for example:
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ExampleActivity.class);
//There is no limit for number of Extras you want to pass to activity
intent.putExtra("buttonNumber", 1);
startActivity(intent);
}
});
ExampleActivity.java
public class ExampleActivity extends Activity {
int pressedButtonNumber;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_poll);
pressedButtonNumber = getIntent().getExtras().getInt("buttonNumber");
switch(pressedButtonNumber){
case 1:
//Do Something for clicking button 1 scenario
break;
}
}
Upvotes: 2