how to go back to previous fragment on pressing manually back button of individual fragment?

后端 未结 10 1501
悲&欢浪女
悲&欢浪女 2020-11-27 04:49

I have only one activity and multiple fragments in my application.

Two main fragment A(left) and B(right).



        
10条回答
  •  猫巷女王i
    2020-11-27 05:42

    I have implemented the similar Scenario just now.

    Activity 'A' -> Calls a Fragment 'A1' and clicking on the menu item, it calls the Fragment 'A2' and if the user presses back button from 'A2', this goes back to 'A1' and if the user presses back from 'A1' after that, it finishes the Activity 'A' and goes back.

    See the Following Code:

    Activity 'A' - OnCreate() Method:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activityA);
    
        if (savedInstanceState == null) {
            Fragment fragInstance;
    
            //Calling the Fragment newInstance Static method
            fragInstance = FragmentA1.newInstance();
    
            getFragmentManager().beginTransaction()
                    .add(R.id.container, fragInstance)
                    .commit();
        }
    }
    

    Fragment : 'A1'

    I am replacing the existing fragment with the new Fragment when the menu item click action happens:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_edit_columns) {
            //Open the Fragment A2 and add this to backstack
            Fragment fragment = FragmentA2.newInstance();
            this.getFragmentManager().beginTransaction()
                    .replace(R.id.container, fragment)
                    .addToBackStack(null)
                    .commit();
    
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    

    Activity 'A' - onBackPressed() Method:

    Since all the fragments have one parent Activity (which is 'A'), the onBackPressed() method lets you to pop fragments if any are there or just return to previous Activity.

    @Override
    public void onBackPressed() {
        if(getFragmentManager().getBackStackEntryCount() == 0) {
            super.onBackPressed();
        }
        else {
            getFragmentManager().popBackStack();
        }
    }
    

    If you are looking for Embedding Fragments inside Fragments, please refer the link: http://developer.android.com/about/versions/android-4.2.html#NestedFragments

提交回复
热议问题