简体   繁体   中英

How do I get an activity go back to the previous activity which is not the parent?

I got activities A, B, and C. They all navigate forward and back fine. During any of these 3 activities I can start a glossary activity. When I go back/up, no matter what the previous activity was, it goes to activity A (it's parent as defined in the manifest). Do I need to change something in the manifest?

    Intent intent = new Intent(this, glossary.class);
    startActivity(intent);

I am not sure if changing anything in the manifest would help. You could try below code where we are overriding the implementation of the "Up" button and calling onBackPressed() .

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
        onBackPressed();
        return(true);
    }
    return(super.onOptionsItemSelected(item));
}

Let me know if this helps !

If you want to go back to the previous Activity on the stack (the one before you start your GlossaryActivity ), you don't need to define the parent Activity of your GlossaryActivity , so you only need to remove this line in the manifest.

Then, when you will press the back button, it will automatically close your current Activity and go back to the previous.

Another point : if you are using the ActionBar or Toolbar arrow that do the same thing as the back button, you should do this in you GlossaryActivity to go back to the previous Activity :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_messages);
    ...
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    ...
}

and

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM