How to use Fragments in an Android app?

Fragments are a crucial component in Android app development, allowing for more flexible UI designs and better use of screen space across various devices. They enable developers to create reusable UI components and manage different states more efficiently.

How to Use Fragments in Your Android App

To integrate fragments into your Android application, follow these steps:

  1. Create a Fragment class that extends the Fragment class.
  2. Define the UI layout for the fragment in an XML file.
  3. Use FragmentManager to add, replace, or remove fragments in the activity.

Example of Fragment Implementation:

        // Step 1: Create a Fragment class
        public class MyFragment extends Fragment {
            @Nullable
            @Override
            public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
                // Inflate the layout file for this fragment
                return inflater.inflate(R.layout.fragment_my, container, false);
            }
        }

        // Step 2: Add Fragment to Activity
        public class MainActivity extends AppCompatActivity {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                
                // Check if the fragment container is available
                if (savedInstanceState == null) {
                    getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.fragment_container, new MyFragment())
                        .commit();
                }
            }
        }
        

By using fragments, your application can adapt to different screen sizes and orientations, enhancing the user experience across devices.


Fragments Android Development UI Components Android App Fragment Implementation