简单实现两个附加到sys.path
的选项卡,通过MainActivity.java
调用设置根布局:
OnStart
CustomPagerAdapter.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public void updateUi(){
setContentView(R.layout.nav_layout);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.addTab(tabLayout.newTab().setText("Navigation"));
tabLayout.addTab(tabLayout.newTab().setText("History"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
FragmentTransaction statekeeper =getSupportFragmentManager().beginTransaction();
statekeeper.addToBackStack(null);
PagerAdapter adapter = new CustomPagerAdapter(getSupportFragmentManager(), this, tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
mDrawerLayout = findViewById(R.id.drawer_layout);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
//setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public void onStart() {
super.onStart();
updateUi(currentUser);
}
}
Fragment1.java:
public class CustomPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
int mNumOfTabs=2;
public CustomPagerAdapter(FragmentManager fm, Context context,int n) {
super(fm);
mContext = context;
this.mNumOfTabs=n ;
}
@Override
// This method returns the fragment associated with
// the specified position.
//
// It is called when the Adapter needs a fragment
// and it does not exists.
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment frag1 = new Fragment1();
return frag1;
case 1:
Fragment frag2= new Fragment2();
return frag2;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
}
在从设置活动到public class Fragment1 extends Fragment {
@Override
public void onStart() {
super.onStart();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout resource that'll be returned
View rootView = inflater.inflate(R.layout.difusion2, container, false);
Log.i("view","inflated");
// Get the arguments that was supplied when
// the fragment was instantiated in the
// CustomPagerAdapter
Bundle args = getArguments();
return rootView;
}
的向上动作之后,两个片段的布局都消失了。
请注意,我的日志显示没有调用MainActivity.java
方法,但是在片段中调用了OnCreateview
方法。
可能是什么原因?