• 多个Fragment在屏幕翻转会重影问题的解决


    fragment使用add和hide而不用replace的方法添加到activity中,如果屏幕翻转可能会又add新的fragment进去,所以会重影。

    如果有一个sparsearray保存fragment,那么在初始化的时候就应该用

        private void initFragment(Bundle savedInstanceState) {
            //set up fragments
    //        fragments.append(MAIN_INDEX, MainFragment.newInstance());
    //        fragments.append(SUCCESS_INDEX, SuccessFragment.newInstance());
    //        fragments.append(FAILED_INDEX, FailedFragment.newInstance());
    //        fragments.append(NONE_INDEX, NoneFragment.newInstance());
            fragments = new SparseArray<>();
            //Main Fragment
            Fragment mainFragment = getSupportFragmentManager().findFragmentByTag(String.valueOf(MAIN_INDEX));
            if (mainFragment == null) {
                mainFragment = MainFragment.newInstance();
            }
            fragments.append(MAIN_INDEX, mainFragment);
            //Success Fragment
            Fragment succcessFragment = getSupportFragmentManager().findFragmentByTag(String.valueOf(SUCCESS_INDEX));
            if (succcessFragment == null) {
                succcessFragment = SuccessFragment.newInstance();
            }
            fragments.append(SUCCESS_INDEX, succcessFragment);
            //Failed Fragment
            Fragment failedFragment = getSupportFragmentManager().findFragmentByTag(String.valueOf(FAILED_INDEX));
            if (failedFragment == null) {
                failedFragment = FailedFragment.newInstance();
            }
            fragments.append(FAILED_INDEX, failedFragment);
            //none Fragment
            Fragment noneFragment = getSupportFragmentManager().findFragmentByTag(String.valueOf(NONE_INDEX));
            if (noneFragment == null) {
                noneFragment = NoneFragment.newInstance();
            }
            fragments.append(NONE_INDEX, noneFragment);
            //add to activity
            for (int i = 0; i < fragments.size(); i++) {
                Fragment f = fragments.valueAt(i);
                if (!f.isAdded())
                    getSupportFragmentManager()
                            .beginTransaction()
                            .add(R.id.container, f, String.valueOf(fragments.keyAt(i)))
                            .hide(f)
                            .commit();
            }
        }

    不直接append新的fragment,而是通过fragmentsupportmanager先检查有没有已有的fragment,这样就可以解决重影问题。

    需要注意的是:setRetainInstance(true)必须设置,这样fragment才不会在manager中销毁,替换fragment后想修改数据才不会出现nullpointerexception错误

  • 相关阅读:
    输出最大值 (10 分)
    对象数组初始化 (10 分)
    2018Final静态成员(黑名单)
    寻找回文子串(python)
    cpp-week_one-错题整理
    Python 读入多个整数
    C语言学习—strcpy()和strcat()
    javascript数学对象、自定义对象10.0
    javascript基础DOM对象6.2
    javascript基础DOM对象6.1
  • 原文地址:https://www.cnblogs.com/matoo/p/4842251.html
Copyright © 2020-2023  润新知