DEV Community

Cover image for Android Fragments
Pete
Pete

Posted on • Updated on

Android Fragments

To understand this article, you need to know that a fragment is a reusable component, it has a layout file that declares its UI and other basic stuff. I'll be showing you how to use it from first principle.

Creating Fragments

All fragments must have a public constructor with no parameters(I'll be calling it a 'public no-arg constructor'). If you create a fragment class without one, you'll get a runtime exception. Java auto-generates a public no-arg constructor at runtime if there are no other constructors in the class but if you declare another constructor in the class, you'll have to declare the public no-arg constructor by yourself.

Fragments have a method named onCreateView(). This method is where the fragment's layout gets inflated. The method signature and body are usually like this:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.<layoutFileName>,container, false);
}
Enter fullscreen mode Exit fullscreen mode

Code Breakdown
We can see that the method takes three arguments - A LayoutInflater instance used to inflate or bind the layout you want to the component, a ViewGroup that represents the portion of the activity's layout that the fragment will be inflated onto, and a Bundle for saving instance state.

Inside the method body, the LayoutInflater calls its inflate() method. Its inflate method takes 3 arguments:

  1. The layout you want to inflate
  2. The ViewGroup passed into onCeateView()
  3. a boolean value called attachToRoot

In summary, the LayoutInflater object creates a View object and the onCreateView method returns the View that's created.

Adding a Fragment To An Activity

To add a fragment to an activity's layout, we add the <fragment/> tag to the activity's xml layout file. The name property of the fragment tag must be the fully-qualified name of the fragment class we want to associate with the layout.

<fragment
    android:name="com.example.demoapp.ExampleFragment"
    android:layout_width="match_parent" />
Enter fullscreen mode Exit fullscreen mode

The code above assumes that we are building an app with the package name com.example.demoapp and that the name of the fragment class is either ExampleFragment.java or ExampleFragment.kt

You can apply other regular xml properties to your <fragment/> tag. If there are no other views in your activity, your fragment can be its root layout.

Next: Getting an Activity and a Fragment to Interact

Top comments (0)