Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigate from one fragment to another on click of a button

Tags:

android

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 ?

like image 591
user1744952 Avatar asked Jan 11 '13 21:01

user1744952


3 Answers

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>
like image 63
Frank Avatar answered Oct 22 '22 02:10

Frank


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.

like image 23
Xcalibur Avatar answered Oct 22 '22 03:10

Xcalibur


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();
like image 2
HARI HARAN Avatar answered Oct 22 '22 03:10

HARI HARAN