I want to navigate from a fragment to another on click of a button and i also want to pass the data. What i should do for that ?
here's an example to help you out:
your_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Fragment frag = new YourFragment(Data yourdata);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, frag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout android:name="fragments.YourInitialFragment"
android:id="@+id/fragment_container"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dip" />
</LinearLayout>
Have a read of the Android documentation on this subject:
All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
In fact if you add a fragment using the Android Studio templates, it will add template code that implements the pattern described in this article using an interface.
To address your specific scenario, your activity would implement an interface like this:
public interface OnFragmentInteractionListener
{
void onButtonClick(Data data);
}
Then in the implementation of that method, the activity could perform the navigation using the FragmentManager as indicated in the other answer. The article gives a much more detailed explanation of this process.
Fragment fragment =null;
switch (view.getId()) {
case R.id.fragMentOneLayout:
fragment = new FragMentOne();
break;
case R.id.fragMentTwoLayout:
fragment = new FragMentTwo();
break;
}
FragmentManager fm = getFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With