How to navigate up to the same parent state

前端 未结 5 634
清歌不尽
清歌不尽 2020-12-02 13:08

From my observation from Gmail and TED app the behavior of up navigation it will navigate to parent with the same state (scroll position) not like what Google say in their d

相关标签:
5条回答
  • 2020-12-02 13:54

    The "standard" behaviour for an android activity is, that a new instance of the activity is created, every time there is a new intent for this activity (see launchMode-docu here). Because of this your extras seem to be gone, if you call navigateUpTo.

    In your case, I would advise to use

    android:launchMode="singleTop"
    

    for your parent activity in your AndroidManifest.xml. This way you will return to your existing activity (as long as it is on the top of the back stack of your task). This way your extras will be preserved.

    I too, do not understand why this is not mentioned in the Google doc you cite, as this seems the behaviour one expects if using up-navigation.

    0 讨论(0)
  • 2020-12-02 13:59

    I had a similar issue when I called startActivityForResult() in my main activity with fragments and then tried to return to it from the callee using Up navigation. Solved by implementing Up navigation as:

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

    In this case Up button behaves like an ordinary Back button and all states are preserved.

    0 讨论(0)
  • 2020-12-02 14:01

    you can use this :

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                super.onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    0 讨论(0)
  • 2020-12-02 14:04

    This is an alternative solution to the accepted answer:

    If you cannot change the launchMode of your activity or if the parent activity is not on top of the back stack (e.g. A is parent of C), you cannot use the solution above. In this case you have to extend your navigateUpTo call to tell the activity, that it should not be recreated, if it is on the back stack:

    Intent intent = NavUtils.getParentActivityIntent(this); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
    NavUtils.navigateUpTo(this, intent);
    
    0 讨论(0)
  • 2020-12-02 14:06

    You would need to save the state on the parent activity and recover it after returning from the calling one.

    See Saving Android Activity state using Save Instance State for a complete explanation of the preocess, with code.

    0 讨论(0)
提交回复
热议问题