To navigate from a second fragment to the first fragment in an Android app, you can use the FragmentManager
and FragmentTransaction
classes to pop the second fragment from the back stack.
Here is an example of how you can navigate from the second fragment to the first fragment by clicking a button:
public class SecondFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_layout, container, false); // find the back button and set an OnClickListener Button backButton = view.findViewById(R.id.back_button); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // get the FragmentManager and start a FragmentTransaction FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // pop the second fragment from the back stack fragmentManager.popBackStack(); // commit the transaction fragmentTransaction.commit(); } }); return view; } }Source:www.lautturi.com
This code defines a SecondFragment
class that extends the Fragment
class, and sets an OnClickListener
for a back button in the fragment's layout. When the button is clicked, the code gets the FragmentManager
object for the current activity and starts a FragmentTransaction
. Then, it calls the popBackStack
method to remove the second fragment from the back stack, and finally, it commits the transaction.
Note that you will need to import the necessary classes and handle any exceptions that might be thrown. You may also need to add the second fragment to the back stack when you navigate to it from the first fragment, using the addToBackStack
method of the FragmentTransaction
object.