Android Fragment 优化与切换

Fragment三个包


    1.android.app.Fragment
    2.android.app.v4.Fragment 向下兼容
    3.androidx.fragment.app.Fragment

Fragment 关键类


    1.FragmentManager 碎片化的管理类
    2.FragmentTransation 操作Fragment做一些事务

FragMent 切换方式


    1.replace 会重新走生命周期 用的较少
    2.show/hide

private void showFragment(Fragment fragment) {
        if (fragment != null) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            hideAllFragment(fragmentTransaction);
            fragmentTransaction.show(fragment);
            fragmentTransaction.commitAllowingStateLoss();
        }
    }

    private void hideAllFragment(FragmentTransaction fragmentTransaction) {
        if (mFraSquare != null) {
            fragmentTransaction.hide(mFraSquare);
        }
        if (mFraMe != null) {
            fragmentTransaction.hide(mFraMe);
        }
        if (mFraChat != null) {
            fragmentTransaction.hide(mFraChat);
        }
        if (mFraStar != null) {
            fragmentTransaction.hide(mFraStar);
        }
    }


Fragment 优化


    onAttachFragment 此方法防止重叠
    场景:当应用内存紧张的时候,系统会回收掉 Frament对象;
    再次进入的时候会重新创建Fragment,并非原来的对象,我们无法控制,导致重叠

    @Override
    public void onAttachFragment(Fragment fragment) {
        if (mFraStar != null && fragment instanceof StarFragment) {
            mFraStar = (StarFragment) fragment;
        }

        if (mFraChat != null && fragment instanceof ChatFragment) {
            mFraChat = (ChatFragment) fragment;
        }

        if (mFraMe != null && fragment instanceof MeFragment) {
            mFraMe = (MeFragment) fragment;
        }

        if (mFraSquare != null && fragment instanceof SquareFragment) {
            mFraSquare = (SquareFragment) fragment;
        }
    }

 

你可能感兴趣的:(android,笔记)