Sobes.tech
Junior — Middle

What methods can be used to create and display a Fragment in an application?

sobes.tech AI

Answer from AI

Creating and displaying a Fragment in Android can be implemented in several ways:

  1. Dynamic addition via FragmentManager:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
transaction.add(R.id.container, fragment);
transaction.commit();
  1. Static addition in XML layout:
<fragment
    android:id="@+id/my_fragment"
    android:name="com.example.MyFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  1. Replacing a fragment:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, new MyFragment());
transaction.addToBackStack(null);
transaction.commit();

The choice of method depends on the task: the static method is simpler but less flexible; the dynamic method allows managing fragments during app runtime.