如何从底部导航栏中打开本身是片段的片段?

时间:2019-10-06 12:10:43

标签: java android

extension=php_openssl.dll

未显示错误,但片段未打开

1 个答案:

答案 0 :(得分:0)

将容器框架布局添加到您的父片段,然后在每次点击设置的片段上使用此:

 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.parent_fragment_container, new ParentFragment());
    ft.commit();

您的代码如下:

   public class HomeFragment extends Fragment {

        BottomNavigationView bottomNavigationView;
    FragmentManager manager = getFragmentManager() ;

        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_home,container,false);
        }
    private void setFragment(Fragment fragment){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.parent_fragment_container,fragment);
        ft.commit();
}
     @Override
        public void onStart() {
            super.onStart();
            bottomNavigationView = bottomNavigationView.findViewById(R.id.bottom_navigation);
            bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
        }

        private BottomNavigationView.OnNavigationItemSelectedListener navListener=
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                        Fragment selectedFragment = null;
                        switch (menuItem.getItemId()){
                            case R.id.nav_home1 :
                                selectedFragment = new Home1Fragment();
                                 setFragment(selectedFragment);
                                break;
                            case R.id.nav_favourites :
                                selectedFragment = new FavouriteFragment();
                                break;
                            case R.id.nav_search:
                                selectedFragment = new SearchFragment();
                                break;
                        }
                        manager.beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
                        return true;
                    }
                };

    }