Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

Clearing the Android back stack

I'm trying to do something similar to this question.

I've got a main app A, and sub-apps B and C. B is a searchable dictionary, and C is a definition, so if you search for many words, you can end up with the stack looking like A > B > C > B > B > C > B > C > C > C... etc

Whenever I go back, I'd like to go back to the original B, so I want the back stack to basically stay at A > B all the time.

I've currently got it set up using an Intent so when the back button is pressed from C, it goes to a new instance of B, but that's obviously not what I want.

Ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Shouldn't hitting BACK from C take you to the original B? So the stack should look like:

A>
  B>
    C<
  B>
    C>
      C<
    C<
  B<
A

with > going to the next activity, and < being the back button?

You could override onBackPressed for all the activities, so for C it loads a new B, B it loads a new A, and A you would do moveTaskToBack(true);, but that's less of a solution and more of a hack to make it work.

Try to use onResume so that B comes up like it would on default. Set any pertinent variables to what they are in a new activity. If you only want this when you're coming from C, have a class boolean that is set to true when C is loaded, and check it in onResume or onRestart. If it's true, set everything to default/blank, and set the boolean to false. If not, load it how it was (this is if they hit home and come back to the app, basically). I'm not at my work desk, but I think you'll want:

@Override
    public void onResume() {
        super.onResume();
        if(fromC == true){
        //Set all variables to load default dictionary
        fromC = false;
        }
    }
}

This should make the original B act like a new B.

Or instead, you could do it the easy way, and when you call the intent to load a new B like this:

startActivity(getIntent());
finish();

That'll make there only be one B. Making it load as a blank when you go back is a little bit different and requires class variables, or some other tricky trick that I am thinking of. This is something like what you'll want to do: .zip of small sample

If you can get your code reworked to something like that almost (where you can use the appropriate variables to set up things to work right if that makes any sense).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...