1、首先了解一下fragment的生命周期

onCreate是指創建該fragment類似於Activity.onCreate,你可以在其中初始化除了view之外的東西,onCreateView是創建該fragment對應的視圖,你必須在這里創建自己的視圖並返回給調用者,例如
return inflater.inflate(R.layout.fragment_settings, container, false);。
super.onCreateView有沒有調用都無所謂,因為super.onCreateView是直接返回null的。
return inflater.inflate(R.layout.fragment_settings, container, false);。
super.onCreateView有沒有調用都無所謂,因為super.onCreateView是直接返回null的。
由上可見fragment的view在從其他fragment切回來后都會被重新創建視圖onCreateView,所以當我們在fragment含有比較復雜且加載數據量較耗時的時候便會在初始化view的時候變得很卡。
所以我便將復雜的view單獨拎出來放在oncreate內,只在父activity創建后初始化一次,然后將這個復雜的view再添加到fragment中。
下面是我的代碼:
private View vv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
goodAdapter = new AdapterCursorGoodList(getActivity());
getActivity().getSupportLoaderManager().initLoader(-1, null, praiseLoaderCallbacks);
vv = LayoutInflater.from(getActivity()).inflate(R.layout.infos_content_item, null);
goodLayout = (InfosListLayout) vv.findViewById(R.id.good_layout);// 解決了每次fragment onCreateView,此處只被new一次
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
goodAdapter = new AdapterCursorGoodList(getActivity());
getActivity().getSupportLoaderManager().initLoader(-1, null, praiseLoaderCallbacks);
vv = LayoutInflater.from(getActivity()).inflate(R.layout.infos_content_item, null);
goodLayout = (InfosListLayout) vv.findViewById(R.id.good_layout);// 解決了每次fragment onCreateView,此處只被new一次
}
private LinearLayout ll_container;// 這個容器是裝goodLayout
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.infos_content, container, false);
scrollView = (ScrollView) v.findViewById(R.id.newsScrollview);
newsLoadMore = (TextView) v.findViewById(R.id.newsLoadMore);
ll_container = (LinearLayout) v.findViewById(R.id.ll_container);
ll_container.addView(vv);
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.infos_content, container, false);
scrollView = (ScrollView) v.findViewById(R.id.newsScrollview);
newsLoadMore = (TextView) v.findViewById(R.id.newsLoadMore);
ll_container = (LinearLayout) v.findViewById(R.id.ll_container);
ll_container.addView(vv);
。。。。。。。。
這個解決方案還不夠好,因為第一次加載還是會卡,希望大家有更好的解決辦法,歡迎指導