SoFunction
Updated on 2025-04-14

Android Fragment usage summary

Guide to using Fragment in Android

Fragment is an important component in Android application development. It represents a part of the UI or behavior in the Activity. You can combine multiple Fragments to build a multi-pane UI in one Activity and reuse a Fragment in different activities.

Basic concepts

Fragment has its own life cycle, but depends on the life cycle of the host activity. Each Fragment has its own layout and behavior.

Create a Fragment

1. Define the Fragment class

public class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Layout of expansion fragment        return (.fragment_my, container, false);
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        (view, savedInstanceState);
        // Initialize the view and logic here    }
}

2. Create the layout file for the Fragment (res/layout/fragment_my.xml)

<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Fragment!" />
</LinearLayout>

Add Fragment to Activity

Method 1: Add in XML layout (static method, not recommended)

<!-- activity_main.xml -->
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment
        android:
        android:name=""
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Method 2: Dynamically add it in the code (recommended)

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        setContentView(.activity_main);
        // Check if the Fragment has been added (prevent repeated additions during rotation)        if (savedInstanceState == null) {
            // Create a Fragment instance            MyFragment fragment = new MyFragment();
            // Start Fragment transaction            getSupportFragmentManager().beginTransaction()
                .add(.fragment_container, fragment) // Add to container                .commit();
        }
    }
}

The corresponding activity_main.xml needs to have a container:

<FrameLayout
    android:
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Fragment transactions

You can perform operations such as adding, removing, and replacing:

// Replace FragmentgetSupportFragmentManager().beginTransaction()
    .replace(.fragment_container, new AnotherFragment())
    .addToBackStack(null) // Allow the user to press the return key to return to the previous Fragment    .commit();

Fragment Lifecycle

Fragment lifecycle method:

  • onAttach() - Called when Fragment is associated with Activity
  • onCreate() - Called when Fragment is created
  • onCreateView() - Create a view hierarchy for a Fragment
  • onActivityCreated() - Activity's onCreate() is called after completion
  • onStart() - Called when Fragment is visible
  • onResume() - Fragment can be called when interacting
  • onPause() - Fragment is no longer called when interactive
  • onStop() - Called when Fragment is not visible
  • onDestroyView() - Called when the view of Fragment is removed
  • onDestroy() - Called when Fragment is no longer used
  • onDetach() - Called when Fragment is disassociated from Activity

Fragment communicates with Activity

1. Fragment calls Activity method

// In Fragmentif (getActivity() instanceof MyActivityInterface) {
    ((MyActivityInterface) getActivity()).doSomething();
}
// Activity implementation interfacepublic interface MyActivityInterface {
    void doSomething();
}

2. Activity calls the Fragment method

MyFragment fragment = (MyFragment) getSupportFragmentManager()
    .findFragmentById(.my_fragment);
if (fragment != null) {
    ();
}

3. Share data using ViewModel (recommended)

// Create a shared ViewModelpublic class SharedViewModel extends ViewModel {
    private final MutableLiveData&lt;String&gt; selected = new MutableLiveData&lt;&gt;();
    public void select(String item) {
        (item);
    }
    public LiveData&lt;String&gt; getSelected() {
        return selected;
    }
}
// Get it in Activity or FragmentSharedViewModel model = new ViewModelProvider(requireActivity()).get();
().observe(this, item -&gt; {
    // Update the UI});

Best Practices

  • useFragment in the package (support library version)
  • Avoid holding citations of Activity directly in Fragment
  • Use interfaces to communicate with Fragment and Activity
  • Consider using ViewModel and LiveData for data sharing
  • Reasonable useaddToBackStack()Management Return to the stack
  • Add tags to Fragment for easy search:.add(, fragment, "TAG")

Advanced Usage

1. Fragment parameter passing

// Pass parameters when creating a Fragmentpublic static MyFragment newInstance(String param) {
    MyFragment fragment = new MyFragment();
    Bundle args = new Bundle();
    ("key", param);
    (args);
    return fragment;
}
// Get parameters in Fragment@Override
public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    if (getArguments() != null) {
        String param = getArguments().getString("key");
    }
}

2. Use Navigation Components to Manage Fragment

// Add dependencies inimplementation ":navigation-fragment:2.3.5"
// Navigate with NavControllerNavController navController = (view);
(.action_to_next_fragment);

This is the end of this article about the use of Android Fragment. For more information about Android Fragment, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!