Junior — Middle
Milliste meetoditega saab rakenduses luua ja kuvada Fragment?
sobes.tech AI
Vastus AI-lt
Creating and displaying a Fragment in Android can be done in several ways:
- Dynamically adding via FragmentManager:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
transaction.add(R.id.container, fragment);
transaction.commit();
- Statically adding in XML layout:
<fragment
android:id="@+id/my_fragment"
android:name="com.example.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
- 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 at runtime.