Go back to specific activity from stack

facetostool picture facetostool · May 23, 2014 · Viewed 11.5k times · Source

I'm trying to do something like file manager. And in action bar I wanna to do folder navigation like in "google drive" app. I need create method which can go to previous activity by number from end, or something like this.

Example:

So if I have stack: [1] -> [2] -> [3] -> [4] -> [5]

And I need go to second: so I need delete [3], [4], and [5] from stack and go to [2].

All activities is one class ContentActivity.java.

How it possible to do?

UPDATE:

Some code how I start activities:

public class ContentActivity extends Activity implements AdapterView.OnItemClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        Intent intent = getIntent();
        String folderToOpen = intent.getStringExtra("folderName");
        fillList(folderToOpen);
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        ...
        Intent intent = new Intent(ContentList.this, ContentList.class);
        intent.putExtra("folderName", item.getName());
        startActivity(intent);
    }
}

Answer

antoniom picture antoniom · May 23, 2014

Assuming that Activity2 is the second activity that you want to go,

Try this:

Intent intent = new Intent(this,Activity2.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

According to Android Documentation about FLAG_ACTIVITY_CLEAR_TOP

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.