Detailed Explanation of Android Fragment Return Stack

Posted by ScotDiddle on Thu, 16 May 2019 19:08:32 +0200

Foreword: This article will explain how the backoff stack in Fragment can return to the previous Activity when pressing the return key. However, when we press the return key, if we don't do any processing, the current Fragment will all exit when pressing the return key. If we want to have the effect of gradual withdrawal of Activity, we need to apply Fragm. Return stack in ent.

Video address:
Code address:

Case effect

Case description

You can open Jingdong by yourselves, and you will find that if you click on the classification, discovery, shopping cart, mine, button, and press the return key, you will go back to the home page first, and then exit the application. Here is the application of Fragment's back-to-stack function. Now I will show you the implementation logic of the back-to-stack.

Method introduction

  • addToBackStack(tag); adds Fragment to the fallback stack
  • popBackStack(); Clears Fragment at the top of the stack in the fallback stack
  • popBackStack(String tag, int i );
    • If i=0, go back to the Fragment layer corresponding to the tag
    • If i=FragmentManager.POP_BACK_STACK_INCLUSIVE, return to the upper level of the Fragment corresponding to the tag
  • popBackStackImmediate immediately clears the top Fragment of the fallback stack
  • getBackStackEntryCount(); Gets the number of fragments in the fallback stack
  • getBackStackEntryAt(int index) Gets Fragment under the index value in the fallback stack

Implementation of Layer-by-Layer Exit Return Stack Effect Code

The layout code, in the layout, writes a FrameLayout to place the container of Fragment s; writes a RadioGroup to place the next few buttons.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@+id/framelayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <RadioGroup
            android:id="@+id/radioGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ff0000"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/rb_home"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1"
                android:button="@drawable/home_selector"
                android:checked="true"
                android:gravity="center_horizontal" />

            <RadioButton
                android:id="@+id/rb_cart"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:button="@drawable/cart_selector" />

            <RadioButton
                android:id="@+id/rb_category"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:button="@drawable/category_selector" />

            <RadioButton
                android:id="@+id/rb_personal"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:button="@drawable/personal_selector" />
        </RadioGroup>
    </LinearLayout>

</LinearLayout>

Code in MainActivity

  • Initialization, in the onCreate method
    • Initialize controls and set listeners
    • Add a Home Fragment
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        // Getting Fragment Managers
        fragmentManager = getSupportFragmentManager();
        // Add fragment1 by default
        addFragment(new Fragment1(), "fragment1");
    }
  • Initialize controls to set listeners for RadioButton
private void initView() {
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        rb_cart = (RadioButton) findViewById(R.id.rb_cart);
        rb_category = (RadioButton) findViewById(R.id.rb_category);
        rb_home = (RadioButton) findViewById(R.id.rb_home);
        rb_personal = (RadioButton) findViewById(R.id.rb_personal);
        // For each RadioButton, click events are set. Note that checkChangeListener is not set for radioGroup here.
        rb_cart.setOnClickListener(this);
        rb_category.setOnClickListener(this);
        rb_home.setOnClickListener(this);
        rb_personal.setOnClickListener(this);

    }

* Replace Fragment when you click the button

/**
     * Replace Fragment in turn according to the button clicked
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.rb_home:
            addFragment(new Fragment1(), "fragment1");
            break;
        case R.id.rb_cart:
            addFragment(new Fragment2(), "fragment2");
            break;
        case R.id.rb_category:
            addFragment(new Fragment3(), "fragment3");
            break;
        case R.id.rb_personal:
            addFragment(new Fragment4(), "fragment4");
            break;
        default:
            break;
        }
    }
  • When adding Fragments, place Fragments in the fallback stack at the same time
public void addFragment(Fragment fragment, String tag) {
        // Open transaction
        FragmentTransaction beginTransaction = fragmentManager
                .beginTransaction();
        // Execute transactions, add Fragment
        beginTransaction.add(R.id.framelayout, fragment, tag);
        // Add to the fallback stack and define Tags
        beginTransaction.addToBackStack(tag);
        // Submission of affairs
        beginTransaction.commit();

    }
  • Listen for the return key in Activity and determine the number of fragments in the current backoff stack. If there is more than one Fragment in the backoff stack, each Fragment will be cleared. If there is only one Fragment left, the Fragment corresponding to the home Fragment will be finished ();
  •  

Exit all the fragmented code left on the home page

The other code is the same as the one above, just need to modify the exit logic. You need to determine how many Fragment s are in the current fallback stack, and use the While loop to exit one by one.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Determine that the current key is the return key
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // Get the number of Fragment s in the current fallback stack
            int backStackEntryCount = fragmentManager.getBackStackEntryCount();
            // There are at least several fragment s in the fallback stack, with the home page at the bottom of the stack
            if (backStackEntryCount > 1) {
                // If the number of fragments in the fallback stack is greater than one, always exit
                while (fragmentManager.getBackStackEntryCount() > 1) {
                    fragmentManager.popBackStackImmediate();
                    //Select the first interface
                    rb_home.setChecked(true);
                }
            } else {
                finish();
            }

        }
        return true;
    }
}

Reprinted from: Detailed Explanation of Android Fragment Return Stack

Topics: Android Fragment