The right posture to add Fragment in Android

Preface:

We will certainly use Fragment in our normal development, and often have some inexplicable problems, such as bug s when rotating the screen or being killed and restarted by the system, which means that you are not adding Fragment properly! Here I summarize my way of adding Fragment to the project, which I call correct posture. If there is something wrong or a better way, please leave a message and point out!

Text:

1, Add the correct pose of a Fragment to an Activity

Code in Activity (apply directly):

//KEY for user ID
public static final String KEY_UID = "KEY_UID";
private HomeFragment HomeFragment;

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

        addDetailFragment(savedInstanceState);
    }

    private void addDetailFragment(Bundle savedInstanceState) {
        //Add Fragment in this way, when rotating the screen and being killed and restarted by the system, there will be no problem
        if (savedInstanceState == null) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();

            if (fm.findFragmentById(R.id.fragment_container) == null) {
                HomeFragment = new HomeFragment();
            } else {
                HomeFragment = (HomeFragment) fm.findFragmentById(R.id.videos_fragment_container);
                ft.remove(HomeFragment);
                fm.popBackStack();
                ft.commit();
                ft = fm.beginTransaction();
            }
            //Pass in some parameters
            Bundle bundle = new Bundle();
            bundle.putLong(KEY_UID, mUserId);
            ......
            HomeFragment.setArguments(bundle);

            ft.add(R.id.videos_fragment_container, HomeFragment);
            ft.commit();
        }
    }

In the layout of Activity:

<FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

2, Correct pose for adding several fragments to an Activity

Now many apps will have three pages: home page, discovery page and my page after they enter the home page. Let me take this as an example. Or look at the code in Activity:

    //Define constants that represent each interface
    public static final int HOME_POS = 0; //home page
    public static final int DISCOVERY_POS = 1; //find
    public static final int MINE_POS = 2; //My

    private HomeFragment mHomeFragment; //Homepage Fragment
    private DiscoveryFragment mDiscoveryFragment; //Fragment found
    private UserInfoFragment mMineFragment; //My Fragment

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Delete old Fragment when state changes
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        Fragment fragment = fm.findFragmentById(R.id.frag_container);
        if (fragment != null) {
            ft.remove(fragment);
            fm.popBackStack();
            ft.commit();
        }
  }
  setSelection(HOME_POS); //First page selected by default

Let's continue to see what the setSelection() method does:

public void setSelection(int position) {

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();

        hideAllFragments(transaction); //Hide all fragments first

        //Then the creation and display of each Fragment
        switch (position) {
            case HOME_POS:
                if (mHomeFragment == null) {
                    mHomeFragment = new HomeFragment();
                    transaction.add(R.id.frag_container, mHomeFragment);
                } else {
                    transaction.show(mHomeFragment);
                }
                mHomeTab.setSelected(true);

                break;
            case DISCOVERY_POS:
                if (mDiscoveryFragment == null) {
                    mDiscoveryFragment = new DiscoveryFragment();
                    transaction.add(R.id.frag_container, mDiscoveryFragment);
                } else {
                    transaction.show(mDiscoveryFragment);
                }
                mDiscoveryTab.setSelected(true);

                break;
            case MINE_POS:
                if (mMineFragment == null) {
                    mMineFragment = new UserInfoFragment();
                    transaction.add(R.id.frag_container, mMineFragment);
                } else {
                    transaction.show(mMineFragment);
                }
                mMineTab.setSelected(true);

                break;
        }

        transaction.commit();
    }

Before displaying a Fragment, I will hide all fragments, so that we can be sure that no errors will be displayed. Let's look at hideAllFragments():

private void hideAllFragments(FragmentTransaction transaction) {
        if (mHomeFragment != null) transaction.hide(mHomeFragment);
        if (mDiscoveryFragment != null) transaction.hide(mDiscoveryFragment);
        if (mMineFragment != null) transaction.hide(mMineFragment);
    }

layout code of Activity:

<FrameLayout
        android:id="@+id/frag_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

OK. If you encounter the problem of adding Fragment later, just copy it directly!

Tags: Fragment Android

Posted on Tue, 31 Mar 2020 18:30:32 -0700 by BooRadLey