安卓开发-底部导航栏切换Fragment进行显示

内容纲要

底部导航栏切换Fragment进行显示

创建Fragment对象

通常会有多个Fragment用于切换
Fragment[] fragments保存为集合

private FrameLayout frame_home;
private Fragment[] fragments;
private HomeFragment homeFragment;
private int lastfragment = 0;

显示Fragment对象

加载Fragment视图

private void initView() {
    //加载Fragment
    homeFragment = new HomeFragment();
    //Fragments集合
    fragments = new Fragment[]{homeFragment};
    //加载FrameLayout布局
    frame_home = (FrameLayout) findViewById(R.id.frame_home);
    //设置fragment到布局
    getSupportFragmentManager().beginTransaction().replace(R.id.frame_home,homeFragment).show(homeFragment).commit();
}

切换Fragment

管理多个Fragment并切换

切换到指定Fragment

//切换fragment
private void switchFragment(int lastfragment, int index) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    //隐藏上个Fragment
    transaction.hide(fragments[lastfragment]);
    if (!fragments[index].isAdded()) {
        transaction.add(R.id.frame_home, fragments[index]);
    }
    transaction.show(fragments[index]).commitAllowingStateLoss();
}

底部导航栏点击事件监听器

//底部导航栏点击响应事件
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_home:
                if (lastfragment != 0) {
                    switchFragment(lastfragment, 0);
                    lastfragment = 0;
                }
                ToastUtil.showToast(getApplicationContext(), "点击了nav_home");
                return true;
            case R.id.nav_zoom:
//                    if (lastfragment != 1) {
//                        switchFragment(lastfragment, 1);
//                        lastfragment = 1;
//                    }
                ToastUtil.showToast(getApplicationContext(), "点击了nav_zoom");
                return true;
            case R.id.nav_user:
                ToastUtil.showToast(getApplicationContext(), "点击了nav_user");
                return true;
            default:
                break;
        }
        return false;
    }
};

发表评论