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错误
时间: 2024-10-18 05:45:07