Sobes.tech
Junior — Middle

What methods can be used to implement fragment creation in an application?

sobes.tech AI

Answer from AI

In Android, creating a fragment can be implemented in several ways:

  1. Via XML layout — declare the fragment inside a layout file using the <fragment> tag. This is a static method, and the fragment is created along with the activity.
<fragment
    android:id="@+id/my_fragment"
    android:name="com.example.MyFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  1. Dynamically via code — create an instance of the fragment and add it to a container using FragmentManager and FragmentTransaction.
MyFragment fragment = new MyFragment();
getSupportFragmentManager().beginTransaction()
    .replace(R.id.fragment_container, fragment)
    .commit();

The dynamic method offers more flexibility, for example, it allows changing fragments during the application's runtime.

What methods can be used to implement fragment… - sobes.tech