SamCurve
SamCurve

Reputation: 11

Fragments layout on Android studio

I am adding layouts to my Project and each time I add a layout it also add another layout that comes with the Word "fragment"... can somebody explain me for what is for? I had look over the web and it explain other kind of fragments...

Upvotes: 1

Views: 11464

Answers (2)

IrishGringo
IrishGringo

Reputation: 4054

This is an Android 0.8 question, using the Activity with Fragment template.

So, how would you go about swapping one fragment in for a second fragment? in the same Frame? Perhaps for a button click, for example. Use case, might be a "connect the dots" questionnaire where the next button goes to the next fragment.

I understand that the answer is FragmentManager and FragmentTransactions. When I do this from with in a click event,

    FragmentManager FM  = getFragmentManager();
    FragmentTransaction FT = FM.beginTransaction();
    FT.replace(R.id.container,  new FRAG02());
    FT.addToBackStack(null);
    FT.commit();

I get an error: must implement OnFragmentInteractionListener

It would seem that there is a SOP way of replacing fragments that I am not aware of. Seems like a related comment.

Upvotes: 0

2Dee
2Dee

Reputation: 8621

Android Studio, when asked to create an Activity, will create 4 things for you :

  • An Activity class
  • a layout file for the Activity class, which will include a FrameLayout serving as the container to place the fragment
  • a Fragment class (created as an innner class inside your Activity)
  • a layout file for your fragment (this is the second layout you see in your project structure), say for example fragment_test.xml

If you look closely, you Activity code will contain something like this :

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_test, container, false);
        return rootView;
    }
}

My guess it that this was done so it guides developers to use fragments for the screen's actual content rather than placing it inside the Activity's layout itself. The Fragment is designed to be a re-usable component, so if you have several layouts for your activity depending on the screen size/orientation, you can re-use the same fragments, just placing them differently inside your Activity layout, which is an excellent practice.

I hope I clarified things a bit ;)

Upvotes: 6

Related Questions