我使用了Viewpager
嵌入式fragment
,并且适应了夜间模式。当我打开夜间模式时,我发现该活动已重建,并且片段当然也是。
数字模式:UiModeManager.setNightMode(android.app.UiModeManager.MODE_NIGHT_YES);
我认为他们正在重新加载专用于夜间模式的资源并重新加载视图。但是,当我初始化recyclerView
(在其中一个片段中)时,它为null。
如果我将所有初始化都放在onCreateView
中,则看起来它已正常初始化。但我从活动中称它为null
MainActivity
:url
// in MainActivity
if (isDarkMode) {
PreferenceUtil.getDefault(MainActivity.this)
.edit().putBoolean(Values.SharedPrefsTag.DARK_MODE, false).apply();
UiModeManager UiModeManager = (UiModeManager) getSystemService(Context.UI_MODE_SERVICE);
UiModeManager.setNightMode(android.app.UiModeManager.MODE_NIGHT_NO);
mMainBinding.navigationView.getMenu().findItem(R.id.dart_mode).setChecked(false);
} else {
PreferenceUtil.getDefault(MainActivity.this)
.edit().putBoolean(Values.SharedPrefsTag.DARK_MODE, true).apply();
UiModeManager UiModeManager = (UiModeManager) getSystemService(Context.UI_MODE_SERVICE);
UiModeManager.setNightMode(android.app.UiModeManager.MODE_NIGHT_YES);
mMainBinding.navigationView.getMenu().findItem(R.id.dart_mode).setChecked(true);
}
public final class MusicListFragment extends BaseListFragment {
public static final String TAG = "MusicListFragment";
public FragmentMusicListBinding mMusicListBinding;
private MyRecyclerAdapter adapter;
private MainActivity mActivity;
@Override
public void reloadData() {
Data.sMusicItems.clear();
Data.sMusicItemsBackUp.clear();
adapter.notifyDataSetChanged();
loadData();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mMusicListBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_music_list, container, false);
loadData();
return mMusicListBinding.getRoot();
}
public void initRecyclerView() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity) {
@Override
protected int getExtraLayoutSpace(RecyclerView.State state) {
return 700;
}
};
linearLayoutManager.setItemPrefetchEnabled(true);
linearLayoutManager.setInitialPrefetchItemCount(15);
adapter = new MyRecyclerAdapter(mActivity, Data.sMusicItems
, new MyRecyclerAdapter.Config(PreferenceUtil.getDefault(mActivity).getInt(Values.SharedPrefsTag
.RECYCLER_VIEW_ITEM_STYLE, 0), true));
mMusicListBinding.includeRecycler.recyclerView.setLayoutManager(linearLayoutManager);
mMusicListBinding.includeRecycler.recyclerView.setHasFixedSize(true);
mMusicListBinding.includeRecycler.recyclerView.setItemViewCacheSize(15);
mMusicListBinding.includeRecycler.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
GlideApp.with(mActivity).resumeRequests();
} else {
GlideApp.with(mActivity).pauseRequests();
}
}
});
mMusicListBinding.includeRecycler.recyclerView.setAdapter(adapter);
}
}
当我设置夜间模式时,MainActivity
将调用initRecyclerView()
的{{1}}方法,但是他将具有空指针。但是对我来说,正常启动应用程序是正常的。