我有下一个序列:
好的,我们这样做。
这就是我在导航中转到下一个片段的方式:
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
中进行此操作,但效果相同。我做错了什么?
答案 0 :(得分:1)
我不确切知道这个片段的作用,但它正在操纵Activity
中的视图。由于片段可能在构建或销毁Activity
视图之前存在,因此可能会尝试获取已被其控制之外的元素销毁和/或修改的视图。如果片段被隔离,那么处理它自己的观点会好得多。