如何正确处理返回屏幕



我有下一个序列:

  • 创造活动;
  • 将碎片放入其中;
  • 转到下一个片段;
  • 使用后退按钮返回到上一个片段。

好吧,让我们开始吧。

这就是我转到导航中的下一个片段的方式:

public static void addFragment(Fragment currentFragment, Fragment fragment, int frameLayout) {
    FragmentTransaction fragmentTransaction = currentFragment.getFragmentManager().beginTransaction();
    fragmentTransaction.replace(frameLayout, fragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}
public static void replaceFragment(Fragment currentFragment, Fragment fragment, int frameLayout) {
    FragmentManager fragmentManager = currentFragment.getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment topFragment = fragmentManager.findFragmentById(frameLayout);
    int transactionsCount = fragmentManager.getBackStackEntryCount();
    if (transactionsCount > 0 && topFragment == currentFragment) {
        fragmentManager.popBackStack();
        fragmentTransaction.replace(frameLayout, fragment);
        fragmentTransaction.addToBackStack(null);
    }   else {
        fragmentTransaction.replace(frameLayout, fragment);
    }
    fragmentTransaction.commit();
}

在第一个片段onCreateView,我加载了一些数据并在完成后隐藏活动指示器

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    LinearLayout homeLayout = new LinearLayout(activity);
    inflater.inflate(R.layout.screen_home, homeLayout);
    setupCategoryButtons();
    setupHomeGenderRadioButton(mainLayout);
    setupMagazinesPreviews(mainLayout);
    return homeLayout;
}
private void setupCategoryButtons() {
    if(categoriesButtons.size() > 0) {
        View categoriesWaitIndicator = activity.findViewById(R.id.categoriesWaitIndicator);
        categoriesWaitIndicator.setVisibility(View.INVISIBLE);
        LinearLayout categoriesButtonsLayout = (LinearLayout)activity.findViewById(R.id.categoryButtonsLayout);
        for(CategoryButton categoryButton : categoriesButtons) {
            categoriesButtonsLayout.addView(categoryButton);
        }
        refreshCategoriesButtons();
    }
}

没什么特别的。而且它工作得很好。直到我返回此屏幕。

当我返回此屏幕时,我NullPointerException这些行:

categoriesWaitIndicator.setVisibility(View.INVISIBLE);
categoriesButtonsLayout.addView(categoryButton);

该应用程序似乎找不到这些视图!我试图在onResume中做到这一点,但它具有相同的效果。我做错了什么?

我不知道

这个片段到底是做什么的,但它正在操纵Activity中的视图。 由于片段可能在构建或销毁Activity视图之前存在,因此它可能会尝试获取已被其无法控制的元素销毁和/或修改的视图。 如果片段是隔离的,这样它就可以处理自己的视图,那就更好了。

最新更新