我有下一个序列:
- 创建活动;
- 将片段放入其中;
- 转到下一个片段;
- 使用后退按钮返回上一个片段。
好吧,让我们做吧。
这就是我在导航中转到下一个片段的方式:
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
但它具有相同的效果。我究竟做错了什么?