我正在使用片段制作标签。这是我生成标签的代码:
private static void addTab(QatarAuctionHomeTabActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
// Attach a Tab view factory to the spec
tabSpec.setContent(activity.new TabFactory(activity));
String tag = tabSpec.getTag();
tabInfo.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
ft.detach(tabInfo.fragment);
ft.commit();
activity.getSupportFragmentManager().executePendingTransactions();
}
tabHost.addTab(tabSpec);
}
这是我的onTabChanged()监听器
public void onTabChanged(String tag) {
// TODO Auto-generated method stub
TabInfo newTab = this.mapTabInfo.get(tag);
if (mLastTab != newTab) {
FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
if (mLastTab != null) {
if (mLastTab.fragment != null) {
ft.detach(mLastTab.fragment);
}
}
if (newTab != null) {
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(this,
newTab.clss.getName(), newTab.args);
ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag);
} else {
ft.attach(newTab.fragment);
}
}
mLastTab = newTab;
// ft.addToBackStack(null);
ft.commit();
this.getSupportFragmentManager().executePendingTransactions();
}
}
我正在添加一个带有Gridview的片段(从web获取数据以加载网格)。但我的问题是当我在选项卡之间导航并在每次加载数据时再次转到网格选项卡。每次调用onCreateview()并加载数据。这是网格视图的代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.product_list_layout, container,
false);
Log.e("oncreateview", "Aise");
initiateServerParameters();
getUserDataFromPreference();
initialize();
setUpGrid();
requestDataFromWeb();
return view;
}
我知道ft.attach(newTab.fragment)方法再次重新创建片段的视图,并导致调用oncreateview()方法。但我不想每次都加载数据。怎么能实现呢?
答案 0 :(得分:-1)
使用片段的onCreate方法命中webservice并仅在list为null或更新时设置适配器... 现在你在OnCreateView中执行此操作,每次选择选项卡时都会调用它。