I have 2 Fragments
.
When I click a button in Fragment 1
here what I do:
- I set the variable
String title = "Lady Gaga"
. - I will show the
Fragment 2
.
When the Fragment 2
is shown, I want to display the title text.
How to do it?
I have 2 Fragments
.
When I click a button in Fragment 1
here what I do:
String title = "Lady Gaga"
.Fragment 2
.When the Fragment 2
is shown, I want to display the title text.
How to do it?
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");
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");
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;
}