I have an activity A - which holds 3 fragments in a Viewpager. Fragment number 1, is a list of news articles, when the user selects a news article from the list, activity B starts and shows the details (title, body, comments) of the article selected. I would like for the user to be able to choose which fragment of activity A he wants to return to, by using the options menu.
Activity A:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case 0:
mPager.setCurrentItem(0);
break;
case 1:
mPager.setCurrentItem(1);
break;
case 2:
mPager.setCurrentItem(2);
break;
}
}
Activity B:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, MainActivity.class);
switch (item.getItemId()) {
case R.id.menu_noticias:
//startActivityForResult(intent, 0);
setResult(0, intent);
finish();
return true;
case R.id.menu_contactos:
//startActivityForResult(intent, 1);
setResult(1, intent);
finish();
return true;
case R.id.menu_cumples:
//startActivityForResult(intent, 2);
setResult(2, intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You shouldn't call startActivityForResult from activity B. From A, you start activity B by calling startActivityForResult and then from B it's enough setting the result and finishing the activity
Activity A:
Intent intent = new Intent();
...
startActivityForResult(intent, 0);
Activity B:
case R.id.menu_noticias:
intent.putExtra("menu", 0);
setResult(RESULT_OK, intent);
finish();
return true;
Then on activity A:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
int menu = data.getExtraInt("menu");
switch (menu) {
case 0:
mPager.setCurrentItem(0);
break;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.