我对我的程序有疑问。
我在操作栏中有 3 个选项卡(由片段组成),每个选项卡都显示不同的视图。这些视图具有从数据库中收集的大量信息以显示图表。问题是每次我从一个选项卡切换到另一个选项卡时,阅读的信息量都很大。问题:有没有办法只创建一次每个视图,然后在它们之间移动?
活动:
String label1 = "one day";
Tab tab = actionBar.newTab();
tab.setText(label1);
TabListener<Tab1Fragment> tl = new TabListener<Tab1Fragment>(this, label1, Tab1Fragment.class);
tab.setTabListener(tl);
actionBar.addTab(tab);
String label2 = "two days";
tab = actionBar.newTab();
tab.setText(label2);
TabListener<Tab2Fragment> tl2 = new TabListener<Tab2Fragment>(this, label2, Tab2Fragment.class);
tab.setTabListener(tl2);
actionBar.addTab(tab);
String label3 = "three days";
tab = actionBar.newTab();
tab.setText(label3);
TabListener<Tab3Fragment> tl3 = new TabListener<Tab3Fragment>(this, label3, Tab3Fragment.class);
tab.setTabListener(tl3);
actionBar.addTab(tab);
选项卡侦听器类:
private class TabListener<T extends Fragment> implements ActionBar.TabListener{
private Fragment fragment;
private final Activity activity;
private final String tag;
private final Class<T> classT;
public TabListener(Activity activityTab, String tagTab, Class<T> classTab) {
activity = activityTab;
tag = tagTab;
classT = classTab;
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (fragment == null) {
fragment = Fragment.instantiate(activity, classT.getName());
ft.add(android.R.id.content, fragment, tag);
} else {
ft.attach(fragment); }
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.detach(fragment);
}
和其中一个片段(3个都是一样的,只是改变了R.layout.**):
public class Tab1Fragment extends Fragment {
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
setRetainInstance(true);
return (LinearLayout) inflater.inflate(R.layout.main, container, false);
谢谢!