1·步骤
//获得fragment管理器
fragmentManager = getSupportFragmentManager();
//初始化fragment
initFragment();
private void initFragment() {
fragments = new ArrayList<>();
fragments.add(new ZhihuFragment());
fragments.add(new WeCatFragment());
fragments.add(new GankFragment());
fragments.add(new GoldFragment());
fragments.add(new VetxFragment());
fragments.add(new LikeFragment());
fragments.add(new SettingFragment());
fragments.add(new AboutFragment());
}
//先显示初始碎片
addZhiFragment();
private void addZhiFragment() {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fl_main, fragments.get(0));
fragmentTransaction.commit();
}
private void switchFragment(int type) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment fragment = fragments.get(type);
//fragment是否添加过
if (!fragment.isAdded()) {
transaction.add(R.id.fl_main, fragment);
}
//隐藏上一个碎片
Fragment lastFragment = fragments.get(lastFragmentType);
transaction.hide(lastFragment);
//显示新的Fragment
transaction.show(fragment);
lastFragmentType = type;
if (lastFragmentType == FragmentType.TYPE_WECHAT || lastFragmentType == FragmentType.TYPE_GANK) {
item.setVisible(true);
} else {
item.setVisible(false);
}
transaction.commit();
}
navi.setNavigationItemSelectedListener方法里
switch (id) {
case R.id.zhihu:
toolbar.setTitle(R.string.zhihu);
//调用fragment
switchFragment(0);
toast = Toast.makeText(getApplicationContext(), "123", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, -20, -1010);
imageView = new ImageView(MainActivity.this);
imageView.setImageResource(R.mipmap.ic_drawer_zhihu);
toast.setView(imageView);
toast.show();
break;
}
网友评论