在Fragment中添加如下代码可以确保在切换暗模式/亮模式后仍然能够保持对根视图的引用:
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView != null) {
((ViewGroup) rootView.getParent()).removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.fragment_layout, container, false);
} catch (InflateException e) {
// ViewGroup already has a parent, just return rootView
}
return rootView;
}