-->

Encrypting your link and protect the link from viruses, malware, thief, etc! Made your link safe to visit.

Android Fragments with Example

A fragment is like a subscreen or subactivities. They are basically reusable components. A fragment is used to control a part of the screen and can be used between multiple activities.

Just like an activity, fragments also have layout. The more functionality you can provide through XML code(less java code) means more chance of its reusability in elsewhere in the app.

We will learn using Fragments through our Pizza App. In our Pizza, we have two fragments. PizzaListFragment will be used to show the list of all available Pizza and PizzaDetailFragment will be used to show the details of Pizza selected by the user.

Android Fragments with Example
Android Fragments with Example

So let's get ready.

Create a new Project named as Pizza App.


We'll start by adding the PizzaModel class to the App. It will help us get the details of pizza. Go to File>New and select Java class.

Code for PizzaModel.java:

package com.example.pizzaapp;

public class PizzaModel {
    private String name;
    private String description;

    public static final PizzaModel[] pizzas={
            new PizzaModel("Lahma Bi Ajeen",
                    "This scrumptious version of pizza, which literally translates into \"meat with dough,\" is brought to you by the Lebanese (other parts of the Middle East call it by other names) and is made with minced onions, usually ground lamb, cumin and yogurt."),
            new PizzaModel("Margherita","The pizza Margherita is just over a century old and is named after HM Queen Margherita of Italy, wife of King Umberto I and first Queen of Italy. It's made using toppings of tomato, mozzarella cheese, and fresh basil, which represent the red, white, and green of the Italian flag."),
            new PizzaModel("Calzone","Calzone means 'stocking' in Italian and is a turnover that originates from Italy. Shaped like a semicircle, the calzone is made of dough folded over and filled with the usual pizza ingredients.\n"),
            new PizzaModel("Stromboli","Many people think that strombolis and calzones are identical. However, this is not really the case. According to WIKI, \"there are several theories regarding the origin of the stromboli. Romano's Italian Restaurant & Pizzeria claims to have originated it in 1950 in Essington, Tinicum Township, just outside of Philadelphia, by Nazzareno Romano. Others claim a stromboli sandwich with chili sauce was invented by Mike Aquino, Sr., in Spokane, Washington, named after the movie Stromboli starring Ingrid Bergman, in 1954.\"\n")
    };

    public PizzaModel(String name, String description) {
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }
}


This class is used to store basic information about Pizza. It contains four Different PizzaModel Objects which we will later on display on one of the fragments in a list.

Next, Create the fragment. Go to File>New>Fragment and select Blank Fragment. Provide the fragment name as PizzaDetailFragment.

Note: Untick the factory and callback checkbox otherwise it will lead to the creation of some new methods and files that we don't need at the moment.

Code for fragment_pizza_detail.xml:


&ltLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".PizzaDetailFragment"&gt


    &ltTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        android:id="@+id/textTitle"
        android:textAppearance="?android:attr/textAppearanceLarge"/&gt

    &ltTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Description"
        android:id="@+id/textDescription"
        /&gt

&lt/LinearLayout&gt
Here I used two textview one represents Pizza Name which is large in size and the other is Pizza Description.
The PizzaDetailFragment class extends the Android Fragment class.
There is the overridden method onCreateView(). It is called when Android needs the fragment's layout.
 It is returning a view by inflater.inflate method. This tells Android which layout the fragment uses.
It works similarly to setContentView of activity. The second argument is the container of type ViewGroup.
It is passed by the activity that uses the fragment. It's the ViewGroup in the activity that the fragment layout needs to be inserted into.

The next step is to add a fragment to an activity's layout. Go to activity_main.xml and add the fragment tag and using the class attribute specify it with the fully qualified(package_name.fragment_name) fragment name.

code for activity_main.xml:


&ltLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"&gt

    &ltfragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.example.pizzaapp.PizzaDetailFragment"
        android:id="@+id/detail_frag"/&gt

&lt/LinearLayout&gt

We got our main activity to display the fragment but till now fragment doesn't actually do anything.

We need to find a way to make communication between activity and fragment so that the fragment could know which pizza details it has to display.

pizzaId is the ID of the pizza selected by the user. We will use the Id to populate the view of the fragment.

Code for PizzaDetailFragment.java:

package com.example.pizzaapp;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 */
public class PizzaDetailFragment extends Fragment {
    private long pizzaId;


    public PizzaDetailFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_pizza_detail, container, false);
    }

    public void setPizzaId(long pizzaId) {
        this.pizzaId = pizzaId;
    }
}


Before a activity make communication with fragment,the activity first needs to get a reference to it.Before getting reference,we first need to get the reference to activity's fragment manager using the activity's getFragmentManager(). You then use its findFragmentById() method to get a reference to the fragment:
getFragmentManager().findFragmentById(R.id.fragment_id)

Code for Mainctivity.java:


package com.example.pizzaapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PizzaDetailFragment pizzaDetailFragment= (PizzaDetailFragment) getSupportFragmentManager().findFragmentById(R.id.detail_frag);
        pizzaDetailFragment.setPizzaId(1);

    }
}


Putting 1 in setPizzaId is done intentionally to ensure app is working fine.
To be continued.....

ST

Social

Recent

⬇⬇Get Your Link⬇⬇