In Android, a Fragment represents a behavior or a portion of the user interface in an Activity. It’s a modular section of an activity, that has its lifecycle, receives its input events, and can be added or removed while the activity is running.
What is a Fragment?
A Fragment is a reusable piece of an Android application’s user interface. It can be considered a modular section of an activity, which has its lifecycle, receives its input events, and can be added or removed while the activity is running.
Fragment Lifecycle
Just like an activity, a Fragment also has a lifecycle containing several callback methods you can override to handle lifecycle events. The Fragment lifecycle includes methods like onAttach()
, onCreate()
, onCreateView()
, onActivityCreated()
, onStart()
, onResume()
, onPause()
, onStop()
, onDestroyView()
, onDestroy()
, and onDetach()
.
Implementing a Fragment
To create a Fragment, you must create a subclass of Fragment
(or an existing subclass of it). In your subclass, you need to override methods that handle various fragment lifecycle events, most importantly onCreateView()
, where you define the layout for the fragment’s user interface.
Here’s a simple example of a Fragment:
public class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_example, container, false);
}
}
Adding a Fragment to an Activity
You can add a fragment to an activity in two ways:
Declare the fragment inside the activity’s layout file: This is useful when you know you want to include the fragment in the layout of the activity.
Programmatically add the fragment to an existing ViewGroup: This gives you flexibility in how you add the fragment to the activity. For example, you might decide to add the fragment only if the activity is being used on a large-screen device.
Example:
MainActivity.java
package in.infovistar.androidfragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import android.content.Context;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import in.infovistar.androidfragment.adapters.ViewPagerAdapter;
import in.infovistar.androidfragment.fragments.AboutFragment;
import in.infovistar.androidfragment.fragments.HomeFragment;
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
tabLayout = findViewById(R.id.tabs);
setupFragments();
}
private void setupFragments() {
viewPagerAdapter.add(new HomeFragment(), "Home");
viewPagerAdapter.add(new AboutFragment(), "About");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:background="@color/purple_500"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
ViewPagerAdapter.java
package in.infovistar.androidfragment.adapters;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragments = new ArrayList<>();
private final List<String> fragmentTitle = new ArrayList<>();
public ViewPagerAdapter(@NonNull FragmentManager fm) {
super(fm);
}
public void add(Fragment fragment, String title) {
fragments.add(fragment);
fragmentTitle.add(title);
}
@NonNull
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return fragmentTitle.get(position);
}
}
HomeFragment.java
package in.infovistar.androidfragment.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import in.infovistar.androidfragment.R;
public class HomeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home"/>
</LinearLayout>
AboutFragment.java
package in.infovistar.androidfragment.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import in.infovistar.androidfragment.R;
public class AboutFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_about, container, false);
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="About Us"/>
</LinearLayout>
Output: