码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-09-27 16:13:50      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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错误

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

标签:

原文地址:http://www.cnblogs.com/matoo/p/4842251.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!