How can i change to a specific fragment by pressing a button?

Viewed 84

I would like to change to a specific fragment by pressing a button. I've watched many videos but nobody shows how to change to a specific fragment when a button is in app_bar_main.xml. I'm using the navigation drawer activity.

public class MainActivity extends AppCompatActivity {

private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    setSupportActionBar(binding.appBarMain.toolbar);
    binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(binding.appBarMain.linearLayout.getVisibility()==View.INVISIBLE){
                binding.appBarMain.linearLayout.setVisibility(View.VISIBLE);
            }
            else
                binding.appBarMain.linearLayout.setVisibility(View.INVISIBLE);
        }
    });
    DrawerLayout drawer = binding.drawerLayout;
    NavigationView navigationView = binding.navView;
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(
            R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
            .setDrawerLayout(drawer)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);


    final Button button = findViewById(R.id.povratna);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        //I want to change fragment by pressing this button.

        }
    });


}
2 Answers

I'm not quite understanding what do you mean by app bar main, but If you are asking about opening another fragment from App's action bar options or Navigation drawer's menu options then you don't have to write any click listeners for opening or switching to another fragment. you need to set action bar using navController using setupActionBarWithNavController

After that, You just have to give same id to the menu item and to the fragment in the navGraph. Like you have a user fragment and you have given it an id fragmentUser in navGraph then you have to give same id to that menu item which you want to use to open this fragment.

Related