Navigate from One Fragment to Another on Click of a Button

Androidx: Using a button in one fragment to navigate to another fragment

Adding on to what Vikas said.
He told that when you need to go from an Activity to Fragment you need the getSupportFragmentManager() like below

@Override
public void onClick(View view){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ProfileFragment()).commit();
}

Note how we need to pass in the class for ProfileFragment() here, its layout fragment_profile will be loaded on its own as you will be setting ProfileFragment() with fragment_profile layout.

Next you may in future want to go from one Fragment to another in which case you will only need to add getActivity() before the getFragmentManager(), so it would become

@Override
public void onClick(View view){

getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ProfileFragment()).commit();
}

How can I move from one fragment to another fragment on button click? (kotlin)

Moving from one fragment to another can be easily achieved using Navigation component.
I would suggest taking a look at this link as a starting point:

https://developer.android.com/guide/navigation/navigation-getting-started

How to move from one fragment to another fragment on button's click in android?

Use Fragment transaction to replace your second fragment with third fragment on button click,
For example,

Fragment thirdFragment = new ThirdFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, thirdFragment);
transaction.addToBackStack(null);
transaction.commit();

Hope it helps!

one Fragment to another Fragment on Button click

Change the fragment name with that in which want to move

Button ID = (Button) rootView.findViewById(R.id.btnHello);
ID.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
HelloFragment NAME = new HelloFragment();
fragmentTransaction.replace(R.id.fragment_container, NAME);
fragmentTransaction.commit();

}
});

Change Fragment name on that button click:-

ABC NAME = new ABC ();

Hot to navigate to home fragment from another fragment

I continued searching for solution to my problem. I came across a solution in https://medium.com/mobile-app-development-publication/learn-android-navigation-component-through-coding-79dc47b240b3 It worked perfectly well and solved white screen issue and also not using explicit method using fragment manager for traversing to another fragment. It was about linking menu items to navigation graph.



Related Topics



Leave a reply



Submit