Reputation: 9136
I want to pass extra to my NextActivity so that a button in NextActivity can have different intents. I am successful with doing this to view different layouts, but no clue on how to do this on a button. Heres the code that has a working setContentView switch;
public class ContentViewer extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getIntent().getExtras();
int chooser = bundle.getInt("Layout");
switch(chooser) {
case 0:
setContentView(R.layout.about);
break;
case 1:
setContentView(R.layout.contact);
break;
case 2:
setContentView(R.layout.contentviewer);
break;
case 3:
setContentView(R.layout.contact);
break;
case 4:
setContentView(R.layout.contact);
break;
case 5:
setContentView(R.layout.contact);
break;
case 6:
setContentView(R.layout.contact);
break;
case 7:
setContentView(R.layout.contact);
break;
case 8:
setContentView(R.layout.contact);
break;
case 9:
setContentView(R.layout.contact);
break;
}
}
}
Now, in these layouts, there is a button with the same ID, but i want it to have different Intents based on different cases(like the setContentView above).
UPDATE Theres MainActivity, it has a listview that passes extra. When an item in the listview is clicked, it will open the NextActivity(like in code). NextActivity has a layout that has a Button. Now, based on which item was clicked on the MainActivity, the Button will have different Intents. For example, if in MainActivity, item 1 was clicked, open NextActivity, override Button to have intent 1. If in MainActivity item 2 was clicked, open NextActivity with override button to have intent 2 INSTEAD of intent 1. Clear enough?
Upvotes: 1
Views: 406
Reputation: 66647
Something like this you may need to be:
int valueFromBundle = get value from bundle here...;
Button ipButton = (Button)findViewById(R.id.my_button);
ipButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch(chooser) {
case 0:
Intent i = new Intent(fromActivity.class, toActivity.class);
startActivity(i);
break;
case 1:
Intent i = new Intent(fromActivity.class, toActivity.class);
startActivity(i);
break;
etc..,
}
}
});
Upvotes: 2
Reputation: 6182
Looks like you are already on the right track.
The first thing you will need to do is make sure your Button has an id in xml android:id="@+id/my_button"
Then after your setContent logic get a reference to that button:
Button myButton = (Button)findViewById(R.id.my_button);
You can then add a onClick listener to that button to handle user clicks:
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Your switch logic should go here!
}
});
In the onClick function you can add your switch logic, you might have a separate extra for this but that is up to you, you can essentially do the same as you did above but call a different intent instead of set the content.
Upvotes: 3