FragmentTab切換Fragment時避免重復(fù)加載UI
來源:程序員人生 發(fā)布時間:2015-01-04 08:53:38 閱讀次數(shù):4390次
原文地址:破曉博客 ? [原創(chuàng)]FragmentTab切換Fragment時避免重復(fù)加載UI
使用FragmentTa時,F(xiàn)ragment之間切換時每次都會調(diào)用onCreateView方法,致使每次Fragment的布局都重繪,沒法保持Fragment原有狀態(tài)。

測試于:Android2.3+
解決辦法:在Fragment onCreateView方法中緩存View
private View rootView = null;// 緩存Fragment view
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView == null) {
rootView = LayoutInflater.from(context).inflate(
R.layout.fragment_category, null);
}
// 緩存的rootView需要判斷是不是已被加過parent,
// 如果有parent需要從parent刪除,要不然會產(chǎn)生這個rootview已有parent的毛病。
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
return rootView;
}
這樣就能夠保證不用重復(fù)加載,處理數(shù)據(jù)問題固然還要根據(jù)數(shù)據(jù)源的情況去判斷是不是加載新的數(shù)據(jù)了。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈