Android TabActivity Back Button Functionality with

2019-06-06 16:59发布

问题:

i have TabActivity in android project which contains some tabs. In each tab i can open various activities, and after open it in a tab i want go back to previous activity in same tab, but default android behavior close my root tab activity. How i can realise behavior that i need?

回答1:

There are a few ways of doing this. The first involves creating a custom GroupActivity that will keep track of the stack from the LocalActivityManager and then extending that class for each of your tabs. For that, check out this tutorial:

http://ericharlow.blogspot.com/2010/09/experience-multiple-android-activities.html

A simpler approach is to keep an array of your tab's subviews within your initial ActivityGroup class and then override the back button. Here's some sample code:

public void replaceContentView(String id, Intent newIntent) {
    View view = getLocalActivityManager()
                    .startActivity(id, newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) 
                    .getDecorView();
    viewList.add(view); // Add id to keep track of stack.
    this.setContentView(view);
}       


public void previousView() {

    if(viewList.size() > 0) {  
        viewList.remove(viewList.size()-1);
        if (viewList.size() > 0)
            setContentView(viewList.get(viewList.size()-1)); 
        else
          initView();
    }else {  
        finish();  
    }  
}

The initView() class holds all of the inflating of the original activity's view. This way, you can call this method to regenerate the original activity if there are no more views in the array.