Android: how to load fragment into FrameLayout

后端 未结 3 801
孤街浪徒
孤街浪徒 2020-12-10 05:09

I\'m starting with Android and in my project I\'m using this BottomBar. Love it, works pretty well. The code of my application is almost identical on to the one he uses in t

相关标签:
3条回答
  • 2020-12-10 05:36

    First you have a mistake in your Fragment transaction line, according with your layout should be:

    transaction.replace(R.id.contentContainer, newFragment); // not R.id.bottomBar
    

    Second, you should use supportFragmentManager instead of fragmentManager to work with support fragments, so implement the following way:

    final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.contentContainer, newFragment);
    transaction.addToBackStack(null);
    transaction.commit();
    
    0 讨论(0)
  • 2020-12-10 05:39
                bottomNavigationView= findViewById(R.id.bottom_navigation);
               bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    
    
    
                   @SuppressLint("NonConstantResourceId")
                   @Override
                   public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                       Fragment temp =null;
                       switch (item.getItemId()) {
                           case R.id.library:
                                temp = new LibraryFragment();
    
                               
                               break;
                           case R.id.search:
                               temp = new SearchFragment();
                               break;
                           case R.id.profile:
                               temp = new UserprofileFragment();
                               break;
                           default:
                       }
                      
    
                   getSupportFragmentManager().beginTransaction().replace(R.id.fragment, temp).commit();
    
    
                            return true;
                   }
               });
    
    
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment,new SearchFragment()).commit();
    
    0 讨论(0)
  • in my case i solve it by using

    androidx.fragment.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    

    replace your

    FragmentTransaction

    0 讨论(0)
提交回复
热议问题