Creating a Fragment Statically

Download source code here: Link

<resources>
    <string name="app_name">FragmentDemo1</string>

    <!-- Placeholder text for this example. -->
    <string name="title1">Hyundai 6000</string>
    <string name="article1">The Hyundai Santa Fe is a sport utility vehicle (SUV) produced by the
        South Korean manufacturer Hyundai since 2000.The Santa Fe was a milestone in the companys
        restructuring program of the late 1990s because the SUV was a hit with American buyers.
        The SUV was so popular that at times, Hyundai had trouble supplying the demand.</string>
    <string name="hello_blank_fragment">Hello blank fragment</string>
    <string name="imageDes">carView</string>
    <!-- Text for the fragment. -->
    <string name="yes">Yes</string>
    <string name="no">No</string>
    <string name="yes_message">ARTICLE: Like</string>
    <string name="no_message">ARTICLE: Thanks</string>
    <string name="question_car">LIKE THE CAR?</string>
    <string name="rating_message">RATE IT</string>

    <!-- Text for the button in FragmentExample2. -->
    <string name="open">Open</string>
    <string name="close">Close</string>

    <!-- Text for the exception message in FragmentCommunicate. -->
    <string name="exception_message">must implement OnFragmentInteractionListener</string>
</resources>

Creating a blank fragment

1. Choose File > New > Fragment > Fragment (Blank).

2. In the Configure Component dialog, name the Fragment SimpleFragment. The Create layout XML option should already be selected, and the Fragment layout will be filled in as fragment_simple.

3. Uncheck the Include fragment factory methods and Include interface callbacks options. Click Finish to create the Fragment.

Dialog box for creating blank fragments

4. Open SimpleFragment, and inspect the code:

All sub classes of Fragment must include a public no-argument constructor as shown.

The Fragment class uses callback methods that are similar to Activity callback methods. For example, onCreateView() provides a LayoutInflater to inflate the Fragment UI from the layout resource fragment_simple.

All @string/ resources is defined in the strings.xml file in the source code

First, we are going to set our fragment layouts

Open fragment_simple.xml. In the layout editor pane, click Text to view the XML.

Here, we are adding multiple RadioButton as a RadioGroup to our application so we can switch between states later in our main activity listeners

Now that we have our fragment, let's add it in activity_main.xml to make it be seen.

Great! Now we can move on to interactions for the fragment.

Adding Interactions for Fragment

In our SimpleFragment class, we need to add actions for our RadioButtons that we added in the xml file earlier.

Last updated