0
votes

I'm trying to figure out how fragments are working. I have 3 classes, MainActivity, Fragment1 and Fragment2.

MainActivity extends SherlockFragmentActivity and

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Fragment1 firstFragment = new Fragment1();
    firstFragment.setArguments(getIntent().getExtras());
    getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container1, firstFragment).commit();

Now, I load Fragment1 into my fragment_container, and it displays nice.

(So main_activity.xml has only one )

Ok, Fragment1 extends SherlockFragment, does nothing more then

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment1layout, container, false);

So I just inflate it from my .xml that has one text view and one button.

Where in the world now can I instance Button, and give him code to replace Fragment1 with Fragment2?

What is the code for that, as I'm now "in Fragment1" so I need to somehow communicate with Fragment holder and tell it "replace me with Fragment2".

Fragment2 also extends SherlockFragment, and does nothing, inflates it's empty .xml

2

2 Answers

1
votes

You have to call your fragment2 from fragment1 like below

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
     View view = inflater.inflate(R.layout.fragment1layout, container, false);
            Button button = (Button)view.findViewById(R.id.yourButton);
            button.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    //Replace your fragment

                }
            });
        return view;
}
0
votes

I'm now "in Fragment1" so I need to somehow communicate with Fragment holder and tell it "replace me with Fragment2".

If you want replace Fragment1 to Fragment2 when you click on button which is into Fragment1:

(best practices)

  1. you should create callbacks from fragment1 to MainActivity like it is described here
  2. into MainActivity place logics which will replace fragment1 to fragment2.

(bad practices)

  1. Create method into MainActivity which will replace one fragment to another for example changeFirstFragmentToAnother()
  2. then when you need to change fragment1 to fragment2 you may call this method manually (from fragment1) like this:

    ((MainActivity)getActivity()).changeFirstFragmentToAnother();