如何限制点击BottomNavigatioView项目一次,不重新加载片段?

时间:2017-03-04 18:18:58

标签: android android-fragments bottomnavigationview

如何将BottomNavigatioView项目的点击限制为仅一次,以便当有人发送该项目时,我的mapfragment不必重新加载?

我目前的解决方案就是这个:

fragmentManager = getSupportFragmentManager();
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment fragment = null;
        Fragment currentFragment = fragmentManager.findFragmentById(R.id.main_container);
        int id = item.getItemId();
        switch (id){
            case R.id.World:
                if (!(currentFragment instanceof MapsFragment)) {
                fragment = new MapsFragment();
                    }
                break;

            case R.id.Friends:
                fragment = new FriendsFragment();
                break;


            case R.id.Chats:
                fragment = new You_Fragment();
                break;
        }
        final FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.main_container, fragment).commit();
        return true;
    }
});

但它不起作用,因为片段抛出Nullpointer。

我可以改变以实现上述目标吗?

1 个答案:

答案 0 :(得分:1)

试试这个!为我工作:

fragmentManager = getSupportFragmentManager();
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment fragment = null;
    Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
    int id = item.getItemId();
    switch (id){
        case R.id.World:
            if (currentFragment instanceof MapsFragment) {

                return false;

            } else {

                fragment = new MapsFragment();

            }
            break;

        case R.id.Friends:
            fragment = new FriendsFragment();
            break;


        case R.id.Chats:
            fragment = new You_Fragment();
            break;
    }
    final FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.replace(R.id.main_container, fragment).commit();
    return true;
    }
});