I have a container in which there are two fragments my 1st fragment is working good now I want to send it to 2nd fragment. This is my 1st Fragment
private cl
First communicate to the activity that hosts the fragment1 using a interface as a callback. Then you can communicate to fragment2.
You find more info and code snippets @
http://developer.android.com/training/basics/fragments/communicating.html
Example :
FragmentOne ---> MainActivity ---> FramentTwo
MainActivity implements the interface ReturnData and overrides senData
public class MainActivity extends Activity implements ReturnData{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentOne newFragment = new FragmentOne();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
@Override
public void sendData(String result) {
// TODO Auto-generated method stub
FragmentTwo newFragment = new FragmentTwo();
Bundle args = new Bundle();
args.putString("key",result);
newFragment.setArguments(args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
activity_main.xml
The layout has a FrameLayout which is a view group to which you add/replace framgents
FragmentOne.java
FragmentOne uses interface as a callback to the activity to communicate value.
public class FragmentOne extends Fragment {
public interface ReturnData
{
public void sendData(String result);
}
ReturnData mCallback;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (ReturnData) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ReturnData");
}
}
TextView tv2;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag1,container,false);
tv2 = (TextView) rootView.findViewById(R.id.textView2);
Button b= (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mCallback.sendData(tv2.getText().toString());
}
});
return rootView;
}
}
frag1.xml
FragmentTwo
public class FragmentTwo extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag2,container,false);
TextView tv1 = (TextView) rootView.findViewById(R.id.textView1);
String text = getArguments().getString("key");
tv1.append(text);
return rootView;
}
}
frag2.xml
Snaps

