![](/img/trans.png)
[英]Android: remove() Fragment--> add() new Fragment of same class again ->onCreateView and onActivityCreated not called?
[英]Fragment Recyclerview onCreateView, onViewCreated or onActivityCreated?
我應該在onCreateView,onViewCreated或onActivityCreated中初始化recyclerview嗎?
我搜索了這三者之間的區別是什么,但是有人說使用onCreateView,有人說使用onViewCreated或onActivityCreated而僅使用onCreateView來增加布局?
這是我的代碼
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
recyclerViewSongs = rootView.findViewById(R.id.recyclerViewSongs);
initRecyclerView();
Log.e(TAG, "onCreateView called!");
return rootView;
}
private void initRecyclerView() {
Main.musicList = Main.songs.songs;
// Connects the song list to an adapter
// (Creates several Layouts from the song list)
allSongsAdapter = new AllSongsAdapter(getContext(), Main.musicList);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerViewSongs.setLayoutManager(linearLayoutManager);
recyclerViewSongs.setHasFixedSize(true);
recyclerViewSongs.setAdapter(allSongsAdapter);
recyclerViewSongs.addOnItemTouchListener(new OnItemClickListeners(getContext(), new OnItemClickListeners.OnItemClickListener() {
@TargetApi(Build.VERSION_CODES.O)
@Override
public void onItemClick(View view, int position) {
Toast.makeText(getContext(), "You Clicked position: " + position, Toast.LENGTH_SHORT).show();
if (! Main.songs.isInitialized())
return;
//Start playing the selected song.
playAudio(position);
}
}));
}
因為您正在使用Fragment
所以onCreateView()
將是最佳選擇。 區別在於onCreateView()
是Activity的onCreate()
的Fragment
等效項,並且在創建View
期間運行,而onViewCreated()
在創建View
之后運行。
然后在Activity
onCreate()
方法完成后調用onActivityCreated()
,如下所示: https : //stackoverflow.com/a/44582434/4409113
設置RecyclerView的最佳級別是onCreateView(),它等效於Activity的onCreate(),因為RecyclerView需要快速以免UI變慢。 因此,onViewCreated()中的RecyclerView將在填充UI之前使UI變慢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.