我的应用程序登录后,我将启动ActivityTwo
。在ActivityTwo中,我立即调用保存我的三个标签的TabView
Fragment
。这是ActivityTwo中的代码,用于调用TabView片段
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
fm = getSupportFragmentManager();
final Bundle bundle = new Bundle();
bundle.putInt("TARGET_FRAGMENT_ID", fragId);
ChooseTab chooseTab = new ChooseTab();
chooseTab.setArguments(bundle);
ft = fm.beginTransaction();
ft.replace(R.id.frame, chooseTab, add);
ft.commit();
});
这是ChooseTab Fragment的代码,它负责设置TabView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.choose_tab, container, false);
//-----------------------------------------------------------------------------------
int position=getArguments().getInt("TARGET_FRAGMENT_ID");
tabLayout = (TabLayout) v.findViewById(R.id.simpleTabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
viewPager = (ViewPager) v.findViewById(R.id.simpleViewPager);
viewPager.setOffscreenPageLimit(3);
final PagerAdapter adapter = new PagerAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setCurrentItem(position);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
adapter.notifyDataSetChanged();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
adapter.notifyDataSetChanged();
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
adapter.notifyDataSetChanged();
}
});
return v;
}
这是PagerAdapter的代码
public class PagerAdapter extends FragmentStatePagerAdapter {
private int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Tab1();
case 1:
return new Tab2();
case 2:
return new Tab3();
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
这是Tab1
onCreateView
的代码
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.current_status, container, false);
fm = getFragmentManager();
LoadData();
});
return v;
}
但是当我运行应用程序并在调用LoadData()时打印一些日志时,可以看到调用了loadData。如何解决呢?