-2

I have 2 Fragments. When I click a button in Fragment 1 here what I do:

  1. I set the variable String title = "Lady Gaga".
  2. I will show the Fragment 2.

When the Fragment 2 is shown, I want to display the title text.

How to do it?

Piyush
  • 18,895
  • 5
  • 32
  • 63
an631a
  • 31
  • 3

3 Answers3

1

you can use bundles to pass data :

            Bundle data = new Bundle();
            data.putString("title", "my title");
            Fragment fragment2 = new Fragment2();
            fragment2.setArguments(data);
            FragmentTransaction agm_ft = getSupportFragmentManager()
                    .beginTransaction();
            agm_ft.replace(R.id.frag_containor, fragment2,
                    "agm_frag");
            agm_ft.addToBackStack(null);
            agm_ft.commit();

and get it back on next fragment:

    Bundle getData = getArguments();
    title = getData.getString("title");
Akshay Paliwal
  • 3,718
  • 2
  • 39
  • 43
  • im having a problem in getSupportFragmentManager(). the error said "cannot find symbol getSupportFragmentManager". i am using fragment and my main is Activity. – an631a Mar 08 '15 at 23:16
  • im having a problem in getSupportFragmentManager(). the error said "cannot find symbol getSupportFragmentManager". i am using fragment and my main is Activity. – an631a Mar 08 '15 at 23:16
  • use FragmentTransaction agm_ft = getActivity().getSupportFragmentManager().beginTransaction(); – Akshay Paliwal Mar 09 '15 at 04:34
0

1) Create a Interface

public interface TitleChangeListener {
    public void onUpdateTitle(String title);
}

2) in Fragment 2

Create a public method

public void setTitle(String title){
    //Do Somthing
   }

3)Let Activity implement Interface TitleChangeListener and override onUpdateTitle

 public void onUpdateTitle(String title){
  fragment2.setTitle(title);
 }

4) In Button onClickListner , 1st Fragment

   TitleChangeListener listener=(TitleChangeListener)getActivity();
   listener.onUpdateTitle("Lady Gaga");
Nooh
  • 1,548
  • 13
  • 21
0

For getting string from one fragment to another you have to use bundles and set them to as arguments like :

//on button click

String title = "Lady Gaga";

        Fragment fr = new Final_Categories_Fragment();
        Bundle b = new Bundle();

        b.putString("title", title);
        fragmentManager.beginTransaction()

                .add(R.id.list_frame, fr, "last").commit();
        fr.setArguments(b);

//Now on another fragment you have to get this argument 
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.sub_child_category_listview,
                container, false);
        ...

    String  title = getArguments().getString("title");
    ...
        return rootView;
    }
Surender Kumar
  • 1,123
  • 8
  • 15