问题
Suppose I have an app which Activity A will show a post and also its comments. If I click one of the comment, it will go to Activity B. So, Activity B will show comment and also replies for that comment. Up until now, I don't have a problem. I just need to set parent Activity for Activity B to Activity A in manifest.xml.
Now, I also have Activity X which will show user profile and also all of their posts and comments. If I click a comment, it will go to Activity B. But, if I click up button, it will go back to Activity X. How to make it go back to Activity A?
By the way, to start Activity A, I need to supply extra data which contains the ID for that post and for every comments, they also have an ID of their post ID.
Is it possible to do the following in Activity B?
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// if come from Activity A:
NavUtils.navigateUpFromSameTask(this);
// else
Intent intent = new Intent(this, ActivityA.class);
intent.putLong("ID", comment.getPostId());
startActivity(intent);
return true;
default:
}
return super.onOptionsItemSelected(item);
}
Or should I use something like TaskStackBuilder to start Activity B from Activity X?
回答1:
There are different approaches to do this. My favorite is to pass the necessary information to the Intent something like this with your setup
Intent intent = new Intent();
String caller = getIntent().getStringExtra(CALLER_ACTIVITY);
if (caller.equals(ActivityA.class.getName())) {
NavUtils.navigateUpFromSameTask(this);
return; // dont need to do anything
} else if (caller.equals(ActivityX.class.getName())) {
intent.setClass(this, ActivityA.class);
}
intent.putExtras(getIntent().getExtras()); // if more info needed
startActivity(intent);
finish();
Another approach would be to use getCallingActivity, but this only works if you started the Activity with startActivityForResult().
If you use AppCompat you can get the caller by using AppCompat.getReferrer()
The behaviour might change of the above options, that's why it's a good idea to use the Intent way.
You would start the ActivityB like this
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra(ActivityB.CALLER_ACTIVITY, this.getClass().getName());
startActivity(intent);
来源:https://stackoverflow.com/questions/45194522/how-to-go-up-to-parent-activity-that-need-to-be-started-with-extras-data